1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tips:bashスクリプトでコマンドが失敗したら、エラーメールを飛ばす

Last updated at Posted at 2017-09-15
hoge.sh
# !/bin/bash

NOTIFY_MAIL_TOS='who@dummy.co.jp'

function sendErrorMail() {
    local body="Error occurred."
    local subject="Error mail !!!"
    mail -s "${subject}" "${NOTIFY_MAIL_TOS}"
}

set -eu
trap "echo 'Error occurred.'; sendErrorMail; exit 1" ERR

## メインの処理

コマンドたち(「メインの処理」以降)で終了コード<>0が発生したときに、trapコマンドが発動してメールが送れます。

trapコマンドも'set -eu'も意外に使われていないことが多いですが、
プログラム(といってもbashスクリプトですが)を書く上でエラーハンドリングは、欠かせないので重宝しています。

'set -e'にしていても、trapコマンドが発動してくれるので、いい感じです。
大量に$?で終了コード判定をしなくても済むので、可読性も高くなります。

蛇足です。
・ おそらくたいていのbashバージョンで利用できると思います。
・ "trap ~~~ ERR"の"ERR"の部分については、シグナルについて確認してください。
・ シグナルの部分を変えると「ユーザーキャンセル時(Ctrl + C)は〇〇〇する」という制御できるようになります。

コメントなどありましたら、いただけると嬉しいです!!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?