如何在 Bash 的同一行上编写具有多个条件的 IF 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6753303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I write an IF statement with multiple conditions on the same line in Bash?
提问by Zach Dziura
I'm writing a script right now in Bash that will execute two SQL queries and analyze that queried data. One of the command line inputs takes in an environment variable, which can be one of three values. If it's not one of those values, the script displays a message that prompts the user to enter in a correct value. However, the script doesn't properly check the value, instead prompting the user. Here is my code:
我现在正在用 Bash 编写一个脚本,该脚本将执行两个 SQL 查询并分析所查询的数据。命令行输入之一接受环境变量,该变量可以是三个值之一。如果它不是这些值之一,脚本会显示一条消息,提示用户输入正确的值。但是,脚本没有正确检查该值,而是提示用户。这是我的代码:
if [[ -z $ENV1 || $ENV1 != "ITF" || $ENV1 != "Prod" || $ENV1 != "QA" ]]
then
read -rp "Please enter the first environment (ITF, Prod, QA): " ENV1
fi
echo $ENV1
I think it's a problem with having multiple ||'s in the if line. How can I go about checking for all for of those conditions?
我认为在 if 行中有多个 || 是一个问题。我该如何去检查所有这些条件?
回答by Manny D
It looks to be a problem with your condition. Even if ENV1is any of your options, one of the conditions will be true. For example, ENV1could be "QA", but ENV1 != "Prod"will still evaluate to true (0). Instead of ||use &&:
看来你的情况有问题。即使ENV1是您的任何选项,其中一个条件也将成立。例如,ENV1可能是“QA”,但ENV1 != "Prod"仍会评估为真 (0)。而不是||使用&&:
if [[ -z $ENV1 || ($ENV1 != "ITF" && $ENV1 != "Prod" && $ENV1 != "QA") ]]
then
read -rp "Please enter the first environment (ITF, Prod, QA): " ENV1
fi
echo $ENV1
回答by evil otto
Consider using caseinstead, it will make the code clearer:
考虑case改用,它会使代码更清晰:
case $ENV1 in
"ITF" | "Prod" | "QA")
echo using $ENV1
;;
"")
read -rp "Please enter the first environment (ITF, Prod, QA): " ENV1
;;
*)
echo $ENV1 is not valid
read -rp "Please enter the first environment (ITF, Prod, QA): " ENV1
;;
esac
回答by glenn Hymanman
This is a good time to use select:
这是使用的好时机select:
select ENV1 in ITF Prod QA; do
case "$ENV1" in
ITF|Prod|QA) break;;
esac
done
Not so DRY though.
不过没那么干。
DRYer version
干衣机版
envs=( ITF Prod QA )
select ENV1 in "${envs[@]}"; do
for e in "${envs[@]}"; do
[[ $ENV1 == $e ]] && break 2
done
done

