I have a script with an error handler and output redirection to syslog:
#!/bin/bash
error_handler() {
echo "Unexpected error ${1} in ${2}, line ${3}, ${4}(): ${5}"
exit "${1:-1}"
}
set -eETuo pipefail
trap 'error_handler "$?" "$0" "$LINENO" "${FUNCNAME[0]:-main}" "$BASH_COMMAND"' ERR
exec > >(logger -p local0.err -t foo -e --id="$$") 2> >(logger -p local0.err -t foo -e --id="$$")
# rest of the script here
This works fine and logs both regular output as well as errors to syslog. However, now I would like to run the script as a cron job and get notified when the job fails. Cron by default sends notifications whenever a cron job produces output, but the redirection causes the script to be completely silent.
I could add ... | tee /dev/tty
or ... >/dev/tty
to error_handler()
so that termination messages would appear on the console, but cron jobs don't have a terminal, so this would only work when running the script interactively.
Of course I could change the script so that the error handler itself would send the e-mail
from="root@$(hostname -f)"
to='me@example.org'
echo "Unexpected error ${1} in ${2}, line ${3}, ${4}(): ${5}" |
tee /dev/stderr |
mailx -r "$from" -c '' -s "$0 failed" "$to"
but that would require an additional program for something that cron can already do by itself.
How can I get my script to generate error output for cron (to trigger failure e-mails) while still logging the full output to syslog?