如果在 bash shell 脚本中使用逻辑运算符,如何比较内部的值

How to compare the values inside if using logical operators in the bash shell script

我有以下 shell 脚本代码:

if [ [ "$prevState" != "\"CANCELED\""] || ["$prevState" = "\"CANCELED\"" & "" = "YES" ] ] 

其中 prevstate 的值为 CANCELED,$1 的值为 NO。但是在 shell 执行中我收到以下错误。

/dir/checks/Check.sh: 30: [: /dir/checks/Check.sh: 30: /dir/checks/Check.sh: missing ]NO: not found

如何在 shell 脚本中使用逻辑 AND 和 OR 运算符比较内部 if。上述条件中的所有变量都是字符串

if 的构造是:

if some_command
then
     # this is executed, if `some_command` returned with 0 exit status
     some_other_command
fi

而且不是 if [ expression ][ 是一个普通程序,可执行,相当于 test 可执行。 程序 [ 在程序 [ 中计算的表达式 被确定为真时以 0 退出状态退出.您可以执行 if /usr/bin/[ "a" = "b" ]if [ "a" = "b" ].

相同的结果

使用 &&|| 您可以“链接”不同的命令 - 它被称为 list 命令。列表中的退出状态为上次执行命令的退出状态。 && 当左边的命令以退出状态 0 返回时运行右边的命令。|| 当左边的命令返回退出状态不同于 0 时运行右边的命令。请注意,执行列表中的命令按顺序 - a || b && c(a || b) && c 不是 a || (b && c).

你可以试试:

# if
#     prevState is not \"CANCELED\" _including the quotes_
#         or
#      first argument is "YES"
# then

if [ "$prevState" != "\"CANCELED\"" ] || [ "" = "YES" ] ; then
      blabla
fi

链接:bash manual list of commands, bash manual conditional constructs, posix test