8

我知道我可以做到这一点...

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。但这感觉有点尴尬。有没有更惯用的方法来做到这一点?

4

3 回答 3

13
if ! diff -q "$f1" "$f2"; then ...
于 2013-02-25T17:45:38.343 回答
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
于 2013-02-25T17:44:59.733 回答
0

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

! EXPRESSION
      EXPRESSION is false

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

diff -q $f1 $f2 || echo "they're different"
于 2013-02-25T17:50:39.410 回答