【问题标题】:Does the Exclamation point represent negation in Bash IF condition?感叹号是否代表 Bash IF 条件下的否定?
【发布时间】:2017-05-20 14:31:33
【问题描述】:

我看到了一些类似

的东西
if ! some-command; then
    #do something
fi

感叹号的作用是什么?我看到如果你使用括号,it can be used for negation

这里的效果是一样的吗?

【问题讨论】:

    标签: bash if-statement conditional


    【解决方案1】:

    man bash 中所述:

    如果保留字! 在管道之前,则该管道的退出状态是上述退出状态的逻辑否定。

    【讨论】:

      【解决方案2】:

      正确。

      这是一个代码示例:

      anny ~> if ! grep $USER /etc/passwd
      More input> then echo "your user account is not managed locally"; fi
      your user account is not managed locally
      
      anny > echo $?
      0
      
      anny >
      

      来源:http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

      【讨论】:

      • echo $? 将始终返回0,因为if...then...fi 块的退出状态为0。尝试使用不同的组合,您会发现即使@987654326 也始终为0 @语句坏了,比如语法错误。
      • 简单来说if...fi块的退出状态是块内列表的退出状态,而不是条件的退出状态。
      猜你喜欢
      • 1970-01-01
      • 2017-05-03
      • 2014-12-16
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 2012-11-01
      相关资源
      最近更新 更多