てきとうなメモ

本の感想とか技術メモとか

bashで一回でもエラーが発生したらスクリプトをエラー終了する

some_command
if [ $? -ne 0 ]
then
  echo "failed to execute some_command"
  exit 1
fi

とか毎回やるのはめんどいので、

err_handler() {
  echo "failed to execute '$BASH_COMMAND'"
  exit 1
}

trap err_handler ERR 

some_command
...

とやればいいか

trapはシグナルをトラップするビルトインコマンドで、ERRは通常のシグナルではなく擬似シグナル。man bashには以下のように書いてある。

If a sigspec is ERR, the command arg is executed whenever a simple command has a non-zero exit status, subject to the following conditions. The ERR trap is not executed if the failed command is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or || list, or if the command's return value is being inverted via !. These are the same conditions obeyed by the errexit option.