Cron send email with STDERR but NOT STDOUT?

Viewed 27656

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.

6 Answers

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.

You are asking incorrect question. When you are using mail(1) to send the email, it is no longer relevant that its in cron. What you actually need is to pipe stderr to stdin of mail. Normal pipe is from stdout to stdin, so simplest way to solve this is redirect:

{ /prog > /dev/null ; } 2>&1 | mail ...

Or in the less-clear way because of confusing order of redirectings:

/prog 2>&1 > /dev/null | mail ...

Related