#!/bin/bash function main() { trap catch ERR echo "[INFO]Main" return 0 } function catch() { echo "[ERROR]Fail" } function finally() { echo "[INFO]Finish" } # Entry Point set -eu trap finally EXIT main
それでは次のように無理やり動かないコマンドをmain関数の中に入れてみる。$ ./main.sh [INFO]Main [INFO]Finish
#!/bin/bash function main() { trap catch ERR echo "[INFO]Main" diff test return 0 } function catch() { echo "[ERROR]Fail" } function finally() { echo "[INFO]Finish" } # Entry Point set -eu trap finally EXIT main
$ ./main.sh [INFO]Main diff: missing operand after `test' diff: Try `diff --help' for more information. [ERROR]Fail [INFO]Finish
#!/bin/bash function main() { trap catch ERR echo "[INFO]Main" return 0 } function catch() { echo "[ERROR]Fail" echo "[INFO]Retry" main } function finally() { echo "[INFO]Finish" } # Entry Point set -eu trap catch ERR trap finally EXIT main
#!/bin/bash function main() { trap catch ERR echo "[INFO]Main" diff test return 0 } function catch() { echo "[ERROR]Fail" echo "[INFO]Retry" main } function finally() { echo "[INFO]Finish" } # Entry Point set -eu trap catch ERR trap finally EXIT main
$ ./main.sh [INFO]Main diff: missing operand after `test' diff: Try `diff --help' for more information. [ERROR]Fail [INFO]Retry [INFO]Main diff: missing operand after `test' diff: Try `diff --help' for more information. [INFO]Finish
#!/bin/bash function main() { trap catch ERR echo "[INFO]Main" lib_main return 0 } function catch() { echo "[ERROR]Retry" main } function finally() { if [ ! $? -eq 0 ]; then TITLE="error" TO=abc@example.com FROM=abc@example.com echo -e "Please check log file." | mail -s "$TITLE" -r "$FROM" "$TO" echo "[ERROR]Alert mail is sent to $TO ." fi echo "[INFO]Finish" } # Entry Point SOURCE_PATH="$(cd $(dirname $0);pwd)" source $SOURCE_PATH/lib.sh set -eu trap finally EXIT main
#!/bin/bash function lib_main() { echo "[INFO]Lib Main" touch "test.log" return 0 }
main.shを実行すると以下のようになる。#!/bin/bash function oneTimeSetUp() { echo "[INFO]Setup" source ./lib.sh } function testLibMain() { lib_main test -e test.log ${_ASSERT_EQUALS_} "TestFileExists" $? 0 } . "path/to/shunit2/shunit2"
test.shを実行すると以下のようになる。$ ./main.sh [INFO]Main [INFO]Lib Main [INFO]Finish
[INFO]Setup testLibMain [INFO]Lib Main Ran 1 test. OK
【楽天ブックスならいつでも送料無料】入門bash第3版 [ キャメロン・ニューハン ] 価格:3,024円(税込、送料込) | デスクの横に置いておいて、困ったときにパラパラめくる辞書のように使えるので割と便利。 |