我有一段代碼說如果一切都執行了,如果郵件失敗的話郵件發送一個錯誤信息的人。
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 ]];
意味着
我有一段代碼說如果一切都執行了,如果郵件失敗的話郵件發送一個錯誤信息的人。
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 ]];
意味着
打破它,簡單的條款。此:
[[ and ]]
表示正在進行真實性測試。這個:
$?
是一個變量,它保存上次運行命令的退出代碼。這:
-ne 0
檢查左邊的東西($?)是「不等於」「零」。在UNIX中,以零成功退出的命令成功,而具有任何其他值(1,2,3 ...至255)的退出失敗。
如果前一個命令返回一個錯誤返回碼先前的命令返回一個錯誤。
我明白了謝謝 –
據推測,該片段是,看起來像部分代碼:
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子句中的命令來執行檢查,代碼幾乎總是更清晰。
實際上在很多情況下甚至沒有必要擁有if條款,只要'cmd || only_executed_when_return_code_from_cmd_is_not_equal_to_success' – Jite
現在感謝 –