2013-11-22 44 views
10

我有一段代碼說如果一切都執行了,如果郵件失敗的話郵件發送一個錯誤信息的人。

if [[ $? -ne 0 ]]; then 
    mailx -s" could not PreProcess files" [email protected] 
else    
    mailx -s" PreProcessed files" [email protected] 
fi 
done 

我是新來的Linux編碼我想了解什麼if [[ $? -ne 0 ]];意味着

回答

10

打破它,簡單的條款。此:

[[ and ]] 

表示正在進行真實性測試。這個:

$? 

是一個變量,它保存上次運行命令的退出代碼。這:

-ne 0 

檢查左邊的東西($?)是「不等於」「零」。在UNIX中,以零成功退出的命令成功,而具有任何其他值(1,2,3 ...至255)的退出失敗。

+0

現在感謝 –

3
if [[ $? -ne 0 ]]; 

正在檢查立即前面這一點,如果條件返回代碼。

  • $?意味着返回代碼
  • $? -ne 0意味着因爲0被視爲成功
+0

因此,簡單來說,它意味着,如果前面的代碼沒有完成其作業郵件的錯誤,如果代碼完成了它的工作只是郵件,對不對? –

+0

是的絕對@Rahulsawant – anubhava

+1

我會補充說,-ne代表「不等於」 – Guido

0

如果前一個命令返回一個錯誤返回碼先前的命令返回一個錯誤。

+0

我明白了謝謝 –

0

據推測,該片段是,看起來像部分代碼:

for var in list of words; do 
    cmd $var 
    if [[ $? -ne 0 ]]; then 
     mailx -s" could not PreProcess files" [email protected] 
    else    
     mailx -s" PreProcessed files" [email protected] 
    fi 
done 

哪些可以(也應該)重新編寫更簡單地爲:

for var in list of words; do 
    if ! cmd $var; then 
    message="could not PreProcess files" 
    else 
    message="PreProcessed files 
    fi 
    mailx -s" $message" [email protected] 
done 

[[ $? -ne 0 ]]子句是這種方法檢查cmd的返回值,但幾乎總是沒有必要明確地檢查$?。如果讓shell通過調用if子句中的命令來執行檢查,代碼幾乎總是更清晰。

+0

實際上在很多情況下甚至沒有必要擁有if條款,只要'cmd || only_executed_when_return_code_from_cmd_is_not_equal_to_success' – Jite