views:

1034

answers:

3

I have some python scripts that run on a daily basis in cron. How can I have cron send me an email ONLY WHEN THERE IS STDERR OUTPUT from my script? I want to be able to mail multiple recipients, and set the subject line individually for each cron entry.

I tried this:

./prog > /dev/null | mail . . .

but it didn't work -- I still receive blank emails when there is no STDERR. Do I need to do this in the script itself?

Sorry if this seems basic, I have googled a lot but can't seem to find this answered succintly.

TIA, Noah

+1  A: 

For cron you don't need to pipe through mail. The cron daemon will automatically mail any output of your command to you. Your crontab entry should look like:

# every minute
* * * * * ./prog >/dev/null

If there is no STDERR output, you won't get any mail.

Shin
"If there is no STDERR output, you won't get any mail."That's true, if I set MAILTO="me@mine". However, it is NOT true if piping to mail(1)."In addition to LOGNAME, HOME, and SHELL, cron will look at MAILTO if it has any reason to send mail as a result of running commands in `this' crontab." -- http://ss64.com/osx/crontab.htmlHowever, I need to set the _subject_ of the mail, and there is no way to do this (IMHO) with cron itself. So I'm stuck using mail, which loops us back to my original question.
Noah
A: 

The -s file test will tell you if a file exists and has size greater than zero.

./prog >/dev/null 2>some/file ; if [ -s some/file ] ; then mail < some/file ; fi
mobrule
I ended up using a variant of this approach. Thanks mobrule
Noah
+1  A: 

mail v1.6 has an option to not send messages with an empty body:

 -E      Do not send messages with an empty body.  This is useful for piping errors from cron(8) scripts.

This might be what you are looking for.

j4y