2013-02-25 98 views
4

我知道我能做到这一点的退出状态...打击“不”:反转命令

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

回答

6
if ! diff -q $f1 $f2; then ... 
+0

哇, 谢谢。我想这很容易。我发誓我花了15分钟阅读bash文档之前发布此没有发现任何东西... – Coquelicot 2013-02-25 17:49:00

1

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

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

或(simplty逆转的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 
1

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

! EXPRESSION 
     EXPRESSION is false 

不明白为什么你需要的否定,因为你处理这两种情况......如果你只需要处理,他们不匹配的情况:

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

这是否实际上调用测试?我没有使用“测试”和“[”。 – Coquelicot 2013-02-25 18:00:23

+1

它没有调用它,它是一个shell内置的(出于性能原因),但是语法是相同的 – 2013-02-25 18:19:52