【问题标题】:Shell script : How if condition evaluates true or falseShell脚本:条件如何评估真或假
【发布时间】:2014-06-26 11:19:43
【问题描述】:

'if' 关键字在内部检查什么环境变量或某些东西来决定真/假。 我有类似以下两个陈述的内容。 abc 已安装,但未安装 pqr

if mount |grep -q "abc"; then echo "export pqr"; fi
if mount |grep -q "pqr"; then echo "export abc"; fi

在上述情况下,我希望第一个语句什么都不做,因为已安装 abc(因此在安装 o/p 中找到行),因此 mount |grep -q "abc" 之后的 $? 为 0。 我希望第二条语句执行回声。但情况并非如此,第一个语句正在打印,但第二个没有。所以想了解判断真/假的依据。 Here is one related question

但该问题的公认答案是:

if [ 0 ]
is equivalent to

if [ 1 ]

如果这是真的,那么我的两个语句都应该回显,对吗?

【问题讨论】:

    标签: linux bash shell scripting


    【解决方案1】:

    您发出的命令与您从引用的问题中得出的类比之间存在基本区别。

    当使用-q 选项执行grep 时,如果找到匹配项,则返回代码为零。这意味着如果mount 的输出包含abc,那么

    if mount |grep -q "abc"; then echo "export pqr"; fi
    

    相当于说:

    if true; then echo "export pqr"; fi
    

    注意这里没有出现test 命令,即[


    引用manual:

    test[ 内置函数使用集合评估条件表达式 基于参数数量的规则。

    0 个参数

    The expression is false.
    

    1 个参数

    The expression is true if and only if the argument is not null.
    

    这解释了为什么 [ 0 ][ 1 ] 都评估为 true。

    【讨论】:

      【解决方案2】:

      if 命令不像 C 语言那样作用于整数的“布尔值”:它作用于后面命令的退出状态。在 shell 中,退出状态为 0 被认为是成功,任何其他退出状态都是失败。如果if 后面的命令以状态0 退出,则为“true”

      例子:

      $ test -f /etc/passwd; echo $?
      0
      $ test -f /etc/doesnotexist; echo $?
      1
      $ if test -f /etc/passwd; then echo exists; else echo does not exist; fi
      exists
      $ if test -f /etc/doesnotexist; then echo exists; else echo does not exist; fi
      does not exist
      

      请注意,[[[(基本上)是(基本上)别名为 test 的命令

      【讨论】:

        【解决方案3】:
        if [ 0 ]
        

        测试字符串0 是否为非空。它是非空的,所以测试成功。同样,if [ 1 ] 成功,因为字符串 1 非空。 [ 命令(也称为 test)正在根据其参数返回一个值。同样,grep 返回一个值。
        if 关键字使shell 根据命令返回的值执行命令,但if 前面的命令的输出无关紧要。

        命令test 0(相当于命令[ 0 ]返回值0。命令test 1也返回值0。shell将零视为成功,所以@的命令987654332@子句被执行。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-08-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-28
          • 2018-07-01
          • 2017-12-18
          相关资源
          最近更新 更多