bash trapコマンド

trap コマンドをシェルスクリプトに組み込むことで、 シグナル受信により実行途中で終了する場合も終了処理を指定することが可能になる。

※java等でのexceptionに近い処理ができる。

#!/bin/bash
# end process
trap 'echo "trapped."; rm -f $TMP_FILE; exit 1' 1 2 3 15

TMP_FILE="/root/test.sh.tmp"
if [ -e $TMP_FILE ]; then
    echo "${TMP_FILE}があるため、処理を終了します。"
    exit 0
fi

# create file
touch $TMP_FILE

sleep 10

rm -f $TMP_FILE

exit

これで、Ctrl+c Ctrl+\ Ctrl+c 強制終了時にも処理を行うことができる。
上記では、重複起動防止用のtmpファイルを強制終了時等にも削除するような処理をいれてある。
テストをしてみるとうまくいった。

参考

http://shellscript.sunone.me/signal_and_trap.html

おすすめの記事