Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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!

share|improve this question

4 Answers 4

up vote 9 down vote accepted

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
share|improve this answer

Cronic (http://habilis.net/cronic/) looks like a good idea; to use it you don't have to change your scripts.

share|improve this answer
    
I really don't see how that will help when the problem is nothing more than an incorrect cron line and cron is doing exactly what it is told to do. –  John Gardeniers Feb 14 '12 at 0:17
    
@JohnGardeniers it helps because sometimes you have output without an error. –  Mikhail Aug 31 at 19:59

You should be directing the stderr anmd not both stdout and stderr.

Use 1> /dev/null not 2>&1 and it should be fine. Also, you may need to report the error correctly in your backup script.

share|improve this answer

You are specifically instructing cron to always send email, even when /bin/backup.sh (don't put it there btw) succeeds. Just omit the | mail -s "Backup status" email@example.com part and email will only be sent when there is output. You can probably (depending on your cron) explicitly set the email address to mail to as an assignment in the crontab file.

For details, see

man 5 crontab
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.