2015-12-14 11 views
2

我正在學習Shell腳本,並且在大多數語言如C,C++中被卡住,0表示false,1表示true,但在下面的shell腳本中,我無法理解,輸出端產生如何使用shell腳本中的if else

if [ 0 ] 
then 
    echo "if" 
else 
    echo "else" 
fi 

不管我寫的東西里面,如果喜歡的而不是0塊,我試過1,2,真的,假的是如果總是運行狀態。這在shell腳本中如何工作。 當if語句內部的表達式爲false時,shell腳本返回什麼結果。

+0

您可能會發現[Shellcheck(http://www.shellcheck.net)是有用的。它會自動指出[此問題](https://github.com/koalaman/shellcheck/wiki/SC2159)。 –

回答

4

它總是執行if一部分,因爲這種情況:因爲它會檢查是否[]之間的字符串不是空/空

[ 0 ] 

永遠是正確的。

正確評價真/假用途:

if true; then 
    echo "if" 
else 
    echo "else" 
fi 
+0

這個表達式返回[10 -gt 100]是什麼,因爲這個字符串不是空的。 –

+0

'10 -gt 100'是一個有效的shell測試條件,它將評估爲false – anubhava

2

Bash中沒有布爾值。 但這裏有一些例子,解釋falsy

  • 空值:「」
  • 計劃與非零代碼退出

一個0在你的例子並不falsy,因爲它是非空值。

空值的例子:

if [ "" ] 
then 
    echo "if" 
else 
    echo "else" 
fi 

用一個例子非零退出代碼(假設沒有名爲 「不存在」 的文件):

if /usr/bin/false 
then 
    echo "if" 
else 
    echo "else" 
fi 

if ls nonexistent &> /dev/null 
then 
    echo "if" 
else 
    echo "else" 
fi 

或者

或者:

if grep -q whatever nonexistent 
then 
    echo "if" 
else 
    echo "else" 
fi