【问题标题】:Bash "not": inverting the exit status of a commandBash "not":反转命令的退出状态
【发布时间】:2013-02-10 22:55:53
【问题描述】:

我知道我能做到……

if diff -q $f1 $f2
then
    echo "they're the same"
else
    echo "they're different"
fi

但是如果我想否定我正在检查的条件怎么办?即像这样的东西(显然不起作用)

if not diff -q $f1 $f2
then
    echo "they're different"
else
    echo "they're the same"
fi

我可以做这样的事情......

diff -q $f1 $f2
if [[ $? > 0 ]]
then
    echo "they're different"
else
    echo "they're the same"
fi

这里我检查上一条命令的退出状态是否大于0。不过这样感觉有点别扭。有没有更惯用的方法来做到这一点?

【问题讨论】:

标签: bash conditional


【解决方案1】:
if ! diff -q "$f1" "$f2"; then ...

【讨论】:

    【解决方案2】:

    如果你想否定,你正在寻找!

    if ! diff -q $f1 $f2; then
        echo "they're different"
    else
        echo "they're the same"
    fi
    

    或(简单地反转 if/else 操作):

    if diff -q $f1 $f2; then
        echo "they're the same"
    else
        echo "they're different"
    fi
    

    或者,尝试使用 cmp 执行此操作:

    if cmp &>/dev/null $f1 $f2; then
        echo "$f1 $f2 are the same"
    else
        echo >&2 "$f1 $f2 are NOT the same"
    fi
    

    【讨论】:

      【解决方案3】:

      否定使用if ! diff -q $f1 $f2;。记录在man test:

      ! EXPRESSION
            EXPRESSION is false
      

      不太清楚为什么需要否定,因为你处理这两种情况......如果你只需要处理它们不匹配的情况:

      diff -q $f1 $f2 || echo "they're different"
      

      【讨论】:

      • 这实际上是在调用测试吗?我没有使用“测试”或“[”。
      • 不是调用它,它是一个内置的shell(出于性能原因),但语法是一样的
      • man test 在这里无关紧要。来自man bash:_如果保留字!在管道之前,该管道的退出状态是上述退出状态的逻辑否定。_
      猜你喜欢
      • 2013-02-28
      • 2010-10-20
      • 2011-07-08
      • 1970-01-01
      • 2014-03-25
      • 2014-12-03
      • 2018-09-18
      • 1970-01-01
      • 2021-10-29
      相关资源
      最近更新 更多