【问题标题】:SHELL - AND operation within IF statementSHELL - IF 语句中的 AND 操作
【发布时间】:2019-09-07 19:17:18
【问题描述】:

假设这些功能:

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

为什么我要进入最后一个 ifstatement ? 我们不应该和01 一样吗?

【问题讨论】:

    标签: bash shell if-statement ksh


    【解决方案1】:

    -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 参考手册

    【讨论】:

      【解决方案2】:

      当你执行时

      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 和 OR 列表是多个管道之一的序列,分别由 &&|| 控制运算符分隔。 AND 和 OR 列表以左结合性执行。 AND 列表的形式为

      command1 && command2
      

      command2 当且仅当command1 返回退出状态为零时才会执行。

      OR 列表具有以下形式

      command1 || command2
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-30
        • 1970-01-01
        • 2021-01-12
        • 2010-12-20
        • 2021-01-27
        • 2012-02-13
        • 2018-10-26
        相关资源
        最近更新 更多