Cron – How to Only Get Errors in Emails

bashcronscheduleshell

I finally set up a realistic backup schedule on my data through a shell script, which are handled by cron on tight intervals. Unfortunately, I keep getting empty emails each time the CRON has been executed and not only when things go wrong.

Is it possible to only make CRON send emails when something goes wrong, ie. my TAR doesn't execute as intended?

Here's how my crontab is setup for the moment;

0 */2 * * * /bin/backup.sh 2>&1 | mail -s "Backup status" email@example.com

Thanks a lot!

Best Answer

Ideally you'd want your backup script to output nothing if everything goes as expected and only produce output when something goes wrong. Then use the MAILTO environment variable to send any output generated by your script to your email address.

MAILTO=email@example.com
0 */2 * * * /bin/backup.sh

If your script normally produces output but you don't care about it in cron, just sent it to /dev/null and it'll email you only when something is written to stderr.

MAILTO=email@example.com
0 */2 * * * /bin/backup.sh > /dev/null
Related Topic