bash 如何在bash中做复杂的条件?('and' &&, 'or' || ...)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10288959/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:07:06  来源:igfitidea点击:

How to do complex conditionals in bash? (mix of 'and' &&, 'or' || ...)

bashsyntaxconditional

提问by Suan

How do I accomplish something like the following in bash?

如何在 bash 中完成类似以下的操作?

if ("$a" == "something" || ($n == 2 && "$b" == "something_else")); then
  ...
fi

回答by Niklas B.

You almost got it:

你几乎明白了:

if [[ "$a" == "something" || ($n == 2 && "$b" == "something_else") ]]; then

In fact, the parentheses can be left out because of operator precedence, so it might also be written as

事实上,括号可以因为运算符优先级而被省略,所以它也可以写成

if [[ "$a" == "something" || $n == 2 && "$b" == "something_else" ]]; then

回答by Suan

if [[ "$a" == "something" ]] || [[ $n == 2 && "$b" == "something_else" ]]; then
  ...
fi