SHELL - IF 语句中的 AND 运算

SHELL - AND operation within IF statement

假设这些功能:

return_0() {
   return 0
}

return_1() {
   return 1
}

然后是下面的代码:

if return_0; then
   echo "we're in" # this will be displayed
fi

if return_1; then
   echo "we aren't" # this won't be displayed
fi

if return_0 -a return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

为什么我要进入最后一个 if声明? 难道我们不应该与那些 01 脱离条件吗?

-atest命令的选项之一([[[也有实现)。所以你不能单独使用 -a 。您可能想使用 &&,它是 AND 列表的控制运算符标记。

if return_0 && return_1; then ...

可以使用-a告诉test到"and"两个不同的test表达式,比如

if test -r /file -a -x /file; then
    echo 'file is readable and executable'
fi

但这相当于

if [ -r /file -a -x /file ]; then ...

这可能更具可读性,因为括号使表达式的 test 部分更清晰。

有关...的更多信息,请参阅 Bash 参考手册

当你执行

if return_0 -a return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

您执行行 return_0 -a return_1。这实际上意味着您将 -areturn_1 作为参数传递给 return_0。如果你想有一个 and 操作,你应该使用 && 语法。

if return_0 && return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

理解这一点的有用信息是:

AND and OR lists are sequences of one of more pipelines separated by the && and || control operators, respectively. AND and OR lists are executed with left associativity. An AND list has the form

command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

An OR list has the form

command1 || command2

command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.