Quieting CRON

From V.S.V., Inc.
Jump to: navigation, search

Scenario

I had a script that ran every 5 minutes in CRON to generate a report if the source information had changed.

*/5 * * * * /home/bshaw/ldap-stats.pl

This worked well. When there was a report, it dumped it to STDOUT. When there wasn't, it would just exit. Since the report went to STDOUT, nobody would see it when it ran so, I decided to have it mailed. Instead of using CRONs default mail capabilities, I had the output redirected to the mail tool so I could give the report a subject and control exactly who got it.

 */5 * * * * /home/bshaw/ldap-stats.pl |mail -s "LDAP Stats report" brian.shaw@vsvinc.com

This also worked well. When there was a report, I got an email. Unfortunately, when there wasn't a report (most of the time) I got a blank email which just cluttered my already overloaded inbox.

After a little bit of searching I came across the solution posted by colucix on linuxquestions.org.

 */5 * * * * /home/bshaw/ldap-stats.pl |(body="$(cat)"; if  -n $body ; then echo "$body" | /bin/mail -s "LDAP Stats report" brian.shaw@vsvinc.com; fi)

This solution grabs the output of the script and checks to see if there is something there. Only if there is does it call the mail tool. This keeps both the local mailbox and your remote mailbox free of the extraneous clutter.