外壳-IF语句中的AND运算

时间:2019-04-17 13:59:38

标签: bash shell if-statement ksh

假设这些功能:

Badminton is a racquet sport played using racquets...

然后输入以下代码:

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 声明? 我们不是应该与那些if0一起摆脱困境吗?

2 个答案:

答案 0 :(得分:4)

-atest命令的选项之一(也由[[[实现)。因此,您不能只使用-a本身。您可能要使用&&,它是AND列表的控制运算符。

if return_0 && return_1; then ...

可以使用-a告诉test“和”两个不同的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参考手册》。

答案 1 :(得分:4)

执行时

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。如果要进行操作,则应使用&&语法。

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

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

  

AND和OR列表是分别由&&||控制运算符分隔的多个管线之一的序列。 AND和OR列表以左关联性执行。 AND列表的格式为

command1 && command2
     

command2仅在command1返回退出状态为零的情况下执行。

     

或列表的格式为

command1 || command2
     

command2仅在command1返回非零退出状态时执行。 AND和OR列表的返回状态是列表中最后执行的命令的退出状态。