How to get cron job to mail output only if non-empty

Matthew Flaschen matthew.flaschen at
Thu Mar 5 01:46:56 UTC 2009

David Karr wrote:
> I have a (root) cron job definition like the following:
> 0 0 * * * /usr/bin/clamscan --no-summary -r --reload
> --log=/var/log/clamav/clamscan.log -i / | mail -s "Virus scan found
> something" davidmichaelkarr at
> This works fine when it finds something (I tested it with a fake virus
> file), but what I didn't expect is that "mail" sends the mail even if the
> output is empty.

You're trying to reinvent the wheel.  Read man cron:

"When  executing  commands, any output is mailed to the owner of the
crontab (or to the user named in the MAILTO environment variable in the
crontab, if such exists)."

Drop the mail -s "Virus scan found something" davidmichaelkarr at
and use MAILTO instead.  cron will only send emails there when there is
actual output.

See also

Matt Flaschen

More information about the ubuntu-users mailing list