trap コマンドは pipe と併用すると動作しない
以下のBashスクリプトがあった場合に、パイプで出力全部ログ吐いちゃおう、 っておもったらうまくERRトラップが動かなくなったので、メモ
動くコード
#!/bin/bash
trap "echo Non-zero exit code detected!" ERR
function fail_please() {
echo "Returning non-zero exit code!"
return 1
}
fail_please# 出力結果
Returning non-zero exit code!
Non-zero exit code detected!動かないコード
#!/bin/bash
trap "echo Non-zero exit code detected!" ERR
function fail_please() {
echo "Returning non-zero exit code!"
return 1
}
fail_please |& tee log_file.log# 出力結果
Returning non-zero exit code!Bash: Trap ERR does not work when pipe operator is used
The ERR trap fires for “simple commands” a pipeline is not a simple command.
パイプはシンプルなコマンドではないらしい
pipefail オプションつければ正常に動く
#!/bin/bash
trap "echo Non-zero exit code detected!" ERR
# trap "echo Non-zero exit code detected!" 0 1 2 3 15
function fail_please() {
echo "Returning non-zero exit code!"
return 1
}
set -o pipefail
fail_please |& tee log_file.logReturning non-zero exit code!
Non-zero exit code detected!メモメモ。。。
