2014-04-15 40 views
1

爲什麼這個工程:Bash -eq和==,什麼是差異?

Output=$(tail --lines=1 $fileDiProva) 
##[INFO]Output = "OK" 

if [[ $Output == $OK ]]; then 
    echo "OK" 
else 
    echo "No Match" 
fi 

,這不?

Output=$(tail --lines=1 $fileDiProva) 
##[INFO]Output = "OK" 

if [[ $Output -eq $OK ]]; then 
    echo "OK" 
else 
    echo "No Match" 
fi 

有什麼區別?在==和-eq之間?

謝謝!

+2

'-eq'用於數字比較,'=='用於字符串比較。顯然第二將失敗。 – anubhava

+0

整數的比較是'-eq'。字符串的比較是'=='。 – Gudgip

+0

閱讀bash文檔(如果你的系統有這個文件,請輸入「info bash」)並搜索'-eq'。 –

回答

5

-eq是一種算術測試。

您正在比較字符串。

help test

Other operators: 

    arg1 OP arg2 Arithmetic tests. OP is one of -eq, -ne, 
       -lt, -le, -gt, or -ge. 

當您使用[[並使用-eq作爲運營商,外殼試圖評估LHS和RHS。下面的例子將解釋它:

$ foo=something 
+ foo=something 
$ bar=other 
+ bar=other 
$ [[ $foo -eq $bar ]] && echo y 
+ [[ something -eq other ]] 
+ echo y 
y 
$ something=42 
+ something=42 
$ [[ $foo -eq $bar ]] && echo y 
+ [[ something -eq other ]] 
$ other=42 
+ other=42 
$ [[ $foo -eq $bar ]] && echo y 
+ [[ something -eq other ]] 
+ echo y 
y 
+0

看不到我的評論,但我編輯了上述響應,以便在變量替換周圍添加雙引號。雙引號將強制未設置或空變量計算爲空字符串。否則,如果-eq比較(如上所述)中的變量爲空或未設置,則會出現語法錯誤。 – George

0

看看this explanation of if

第一個==位於字符串比較運算符的部分,它只能比較兩個字符串。

第二個-eq位於最後一部分ARG1 OP ARG2(最後一個),其文檔說明"ARG1" and "ARG2" are integers

0

-eq,-lt,-gt僅用於算術值比較(整數)。

==用於字符串比較。

相關問題