在 bash shell 脚本中使用复合条件

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

using compound conditions in bash shell script

bashshellcomparison

提问by Sanjan Grero

I want to do something like below in bash script. how do i implement in bash syntax.

我想在 bash 脚本中做类似下面的事情。我如何在 bash 语法中实现。

if !((a==b) && (a==c))
then 
do something
end if

回答by Paused until further notice.

For numeric comparison, you can do:

对于数字比较,您可以执行以下操作:

if ! (( (a == b) && (a == c) ))

For string comparison:

对于字符串比较:

if ! [[ "$a" == "$b" && "$a" == "$c" ]]

In Bash, the double parentheses set up an arithmetic context (in which dollar signs are mostly optional, by the way) for a comparison (also used in for ((i=0; i<=10; i++))and $(())arithmetic expansion) and is used to distinguish the sequence from a set of single parentheses which creates a subshell.

在bash,双括号设置算术上下文(其中美元符号大多是可选的,通过的方式)用于比较(在也使用for ((i=0; i<=10; i++))$(())算术膨胀)和用于将序列从一组单括号其产生分辨一个子外壳。

This, for example, executes the command trueand, since it's always true it does the action:

例如,这将执行命令,true并且由于它始终为真,因此执行以下操作:

if (true); then echo hi; fi 

This is the same as

这与

if true; then echo hi; fi

except that a subshell is created. However, if ((true))tests the value of a variable named "true".

除了创建了一个子shell。但是,if ((true))测试名为“true”的变量的值。

If you were to include a dollar sign, then "$true" would unambiguously be a variable, but the ifbehavior with single parentheses (or without parentheses) would change.

如果您要包含一个美元符号,那么“$true”将毫无if疑问地成为一个变量,但带有单括号(或不带括号)的行为会发生变化。

if ($true)

or

或者

if $true

would execute the contents of the variable as a command and execute the conditional action based on the command's exit value (or give a "command not found" message if the contents aren't a valid command).

将变量的内容作为命令执行,并根据命令的退出值执行条件操作(如果内容不是有效命令,则给出“未找到命令”消息)。

if (($true)) 

does the same thing as if ((true))as described above.

做与上述相同的事情if ((true))

回答by wilhelmtell

if [ "$a" != "$b" -o "$a" != "$c" ]; then
  # ...
else
  # ...
fi

回答by SiegeX

#!/bin/bash

a=2
b=3
c=4

if ! (( (a == b) && (a == c) )); then  
  # stuff here
fi

You could also use the following which I personally find more clear:

您还可以使用以下我个人觉得更清楚的内容:

#!/bin/bash

a=2
b=3
c=4

if (( (a != b) || (a != c) )); then  
  # stuff here
fi

Technically speaking you don't need the parens around the sub expressions since the equality operators == !=have higher precedence then both the compound comparison operators && ||but I think it's wise to keep them in there to show intent if nothing else.

从技术上讲,您不需要子表达式周围的括号,因为相等运算符的== !=优先级高于复合比较运算符,&& ||但我认为将它们保留在那里以显示意图是明智的。