盲目的に終了する代わりにエラーを処理できるようにするには、set -e
を使用する代わりに、ERR
擬似信号でtrap
を使用します。
#!/bin/bash
f() {
errcode=$? # 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 $errcode # 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シグナルに加えて、他のバッシュ疑似信号RETURN
とDEBUG
を含む他の信号を処理するように設定することができます。ここで
あなたはABSを好きなら、あなたは[BashGuide](http://mywiki.wooledge.org/BashGuide)を好きになる、[BashFAQ]( http://mywiki.wooledge.org/BashFAQ)と[BashPitfalls](http://mywiki.wooledge.org/BashPitfalls)を参照してください。 –