2012-12-10 45 views

回答

17

這裏有一些常見的形式。最好選擇哪一個取決於你做什麼。您可以在單個腳本中使用任何子集或它們的組合,而不會造成不良風格。


if ! failingcommand 
then 
    echo >&2 message 
    exit 1 
fi 

failingcommand 
ret=$? 
if ! test "$ret" -eq 0 
then 
    echo >&2 "command failed with exit status $ret" 
    exit 1 
fi 

failingcommand || exit "$?" 

failingcommand || { echo >&2 "failed with $?"; exit 1; } 
+0

你可能會考慮追加>&2給echo命令,將它發送到stderr而不是stdout。否則完美的答案。 +1 – Nemo

+0

當調用'exit'時,不帶參數的'exit'與'exit $?'相同。 – jordanm

+0

@jordanm - 除了這些例子,$?將通過調用「echo」本身進行修改。所以一個簡單的'exit'將退出狀態爲零。 – Nemo

5

你可以這樣做:

git clone [email protected]:my-username/my-repo.git || exit 1 

或者exec它:

exec git clone [email protected]:my-username/my-repo.git 

後者將允許採取的shell進程在由克隆操作,如果失敗,回一個錯誤。你可以找到更多關於exec here的信息。

+0

幾乎工作,但我怎麼能 「在這裏錯誤消息」 添加回聲然後運行'退出1'?我試過:'||在這裏回顯「錯誤消息」&& exit 1',但它總是退出,即使成功。謝謝。 – Justin

+0

您需要'failingcommand || {echo message && exit 1; }因爲'&&'沒有比'||'更強的綁定。然後你最好使用'failingcommand || {echo消息;出口1; }' –

0

方法1:

git clone [email protected]:my-username/my-repo.git || exit 1 

方法2:

if ! (git clone [email protected]:my-username/my-repo.git) then 
    exit 1 
    # Put Failure actions here... 
else 
    echo "Success" 
    # Put Success actions here... 
fi