Send mail from a shell script on exit/death
The -e setting in bash is fantastic: die on the first command that fails to return 0 (success). We can couple this with the trap command to trap the EXIT signal when the script exits, and automatically send an e-mail when the script exits.
#!/bin/bash
set -e
#export EMAIL_RECIPIENTS="mwood@somesoftware.com someoneelse@somesoftware.com someoneelse2@somesoftware.com"
export EMAIL_RECIPIENTS="mwood@somesoftware.com"
export SEND_EMAIL="true"
# call like this:
# send_email "this is the subject" "this is the message"
send_email() {
if [ -z "${SEND_EMAIL}" ]; then
return
fi
local subject=$1
local msg=$2
if [ -z "$subject" ]; then
msg="no subject"
fi
if [ -z "$msg" ]; then
msg="no message"
fi
cat << EOF | fmt | mail -s "$subject" $EMAIL_RECIPIENTS
The blah script says:
$msg
EOF
}
trap "echo 'I die'; send_email 'this is the subject' 'this is the message'" EXIT HUP INT QUIT TERM
# send_email 'this is the subject' 'this is the message'
ls ./var
ls ./baz # this dir does not exist, so -e makes us stop, and trap sends an e-mail; nice!
ls ./src