Send mail to root when crontab command fails to run

Got a script that gets executed by crontab as the Apache user. Had a problem with my deployment script where it didn't give the Apache user permissions to execute the script after deploying it. Crontab would call the script and it would silently fail because the Apache user didn't have permissions to run it.

I wanted to get notified when this happened outside of the normal notifications the script itself does, in case script fails to run altogether.

Adding || mail -s "Error $? running $_" root to my script achieved this. What it does is emails root with the exit code and the command name in the subject line, e.g.:

Subject: Error 126 running drush.cron

Bash exit code 126 means command not executable, e.g. permission denied. Here's a list of Bash exit codes with special meanings.

Example of how it looks in /etc/crontab:

*/15 *  * * *   www-data        drush.cron || mail -s "Error $? running $_" root

Another example with script's normal output (stdout) being discared (e.g. mail sent only if script exits with an error or script execution fails in the first place):

*/15 *  * * *   www-data        drush.cron 1>/dev/null || mail -s "Error $? running $_" root

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).