2013-02-25 46 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