如何在 Bash 的复杂条件表达式中使用逻辑非运算符?

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

How to use logical not operator in complex conditional expression in Bash?

bashconditionallogical-operators

提问by wiswit

I would like to have the logical not for the following condition expression in bash, how can I do this?

我想在 bash 中为以下条件表达式设置逻辑 not,我该怎么做?

if [[ $var==2 || $var==30 || $var==50 ]] ; then
  do something
fi

how can I prepend the logical not directly in the above expression, it's very tedious to change it again into things like this:

如何在上面的表达式中不直接添加逻辑,再次将其更改为这样的内容非常繁琐:

if [[ $var!=2 && $var!=30 && $var==50 ]] ; then
  do something
fi

thanks for any hints!

感谢您的任何提示!

回答by konsolebox

if ! [[ $var == 2 || $var == 30 || $var == 50 ]] ; then
  do something
fi

Or:

或者:

if [[ ! ($var == 2 || $var == 30 || $var == 50) ]] ; then
  do something
fi

And a good practice is to have spaces between your conditional operators and operands.

一个好的做法是在条件运算符和操作数之间留有空格。

Some could also suggest that if you're just comparing numbers, use an arithmetic operator instead, or just use (( )):

有些人还可能建议,如果您只是比较数字,请改用算术运算符,或者仅使用(( ))

if ! [[ var -eq 2 || var -eq 30 || var -eq 50 ]] ; then
  do something
fi

if ! (( var == 2 || var == 30 || var == 50 )) ; then
  do something
fi

Although it's not commendable or caution is to be given if $varcould sometimes be not numeric or has no value or unset, since it could mean 0 as default or another value of another variable if it's a name of a variable.

尽管$var有时可能不是数字或没有值或未设置,这不是值得称赞或要注意的,因为它可能意味着 0 作为默认值或另一个变量的另一个值(如果它是变量的名称)。