2012-12-10 3 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

echoコマンドに>&2を追加してstdoutの代わりにstderrに送ることを検討することもできます。そうでなければ完璧な答え。 +1 – Nemo

+0

'exit'を呼び出すとき、argsなしで' 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 

後者はシェルプロセスは、クローン操作によって引き継がれることを可能にする、それが失敗した場合に、リターンエラー。 exec hereについて詳しく知ることができます。

+0

はほとんど作業が、どのように私は 'の出口を実行し、 "ここでエラーメッセージ" エコーを追加することができます1 '?私は試みた: '||エコー "ERROR message here" && exit 1'ですが、成功しても常に終了します。ありがとう。 – Justin

+0

'failingcommand ||が必要です。 {エコーメッセージ&& exit 1; '&&'は '||'よりも強くバインドされないので、そして、 'failingcommand || {エコーメッセージ;出口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 
関連する問題