回答:
お探しexitですか?
これは最高のbashガイドです。 http://tldp.org/LDP/abs/html/
コンテキスト:
if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
echo $jar_file signed sucessfully
else
echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
exit 1 # terminate and indicate error
fi
...
set -eスクリプトを入力した場合、スクリプトは、スクリプト内のコマンドが失敗するとすぐに(つまり、コマンドがゼロ以外のステータスを返したときに)終了します。これはあなた自身のメッセージを書くことを許しませんが、多くの場合、失敗したコマンド自身のメッセージで十分です。
このアプローチの利点は、自動化されていることです。エラーケースへの対処を忘れるリスクを冒す必要はありません。
ステータスが条件付き(if、&&またはなど||)でテストされるコマンドは、スクリプトを終了しません(そうでない場合、条件は無意味になります)。失敗が問題にならない臨時のコマンドのイディオムはcommand-that-may-fail || trueです。でset -eスクリプトの一部をオフにすることもできset +eます。
-xフラグを頻繁に使用する-eで、プログラムが終了する場所を追跡できます。これは、スクリプトのユーザーが開発者でもあることを意味します。
を使用せずに、盲目的に終了する代わりにエラーを処理できるようにしたい場合は、疑似信号でset -ea trapを使用しERRます。
#!/bin/bash
f () {
errorCode=$? # save the exit code as the first thing done in the trap function
echo "error $errorCode"
echo "the command executing at the time of the error was"
echo "$BASH_COMMAND"
echo "on line ${BASH_LINENO[0]}"
# do some error handling, cleanup, logging, notification
# $BASH_COMMAND contains the command that was being executed at the time of the trap
# ${BASH_LINENO[0]} contains the line number in the script of that command
# exit the script or return to try again, etc.
exit $errorCode # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff
他のトラップは、通常のUnixシグナルに加えて他のBash疑似シグナルRETURNやを含む他のシグナルを処理するように設定できますDEBUG。
これを行う方法は次のとおりです。
#!/bin/sh
abort()
{
echo >&2 '
***************
*** ABORTED ***
***************
'
echo "An error occurred. Exiting..." >&2
exit 1
}
trap 'abort' 0
set -e
# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0
echo >&2 '
************
*** DONE ***
************
'
exit 1は、あなたが必要とすることすべてです。これ1は戻りコードなので、たとえば、1実行が成功-1したことを意味し、失敗などを意味するように変更することができます。
testor &&またはを使用するときに役立ちます||。