Bash中的“not”:反转命令的退出状态

9

I know I can do this...

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,但这种方式感觉有些笨拙。是否有更常用的方法?


1
规范的可能是 *如何否定进程的返回值?*? - Peter Mortensen
3个回答

13
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

0

要进行否定,使用if ! diff -q $f1 $f2;。在man test中有记录:

! EXPRESSION
      EXPRESSION is false

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

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

1
这是否实际调用了测试?我没有使用“test”或“[”。 - Coquelicot
1
这不是调用它,而是一个 shell 内建命令(出于性能原因),但语法是相同的。 - Karoly Horvath
2
这里与“man test”无关。从“man bash”中: 如果保留字!在管道之前,那么该管道的退出状态是如上所述的退出状态的逻辑取反。 - Pawel Veselov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接