Bash – cron does not follow bash script’s instruction to send mail conditionally

bashcronemail

I am having trouble getting cron to email an attachment based on a predefined condition set in the bash script. The following is my /etc/crontab setting:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=account@email.com
MAILFROM=cron@server.com
0,30 * * * * root /some/bash/script

The bash script contains:

#!/bin/bash
PATH=/bin:/sbin:/usr/sbin:/usr/bin:/usr/local/bin
if [ -s /var/log/test ]; then
 echo "test" | mailx -s "test" -a /var/log/test -r cron@server.com account@email.com
fi
exit 0

The problem is that cron sometimes send out an email despite the test file being empty. Sometimes the subject header "test" is overridden by cron with its own subject header. Without setting "MAILFROM", cron will use root despite the setting in mailx.

I am very new to cron, so I am not very sure whether I have done things correctly. Would appreciate if somebody can point out what is causing the problem.

Best Answer

You need to understand that cron won't just discard output generated by a job. If a cron job generates output that is otherwise not handled (eg, by mailing it to someone, or putting it into a file, or in some other way) this output will be emailed as described in the MAILTO variable. If you don't want this to happen, you need to make sure that no output can fall out of the end of your job; that's why it's very common to see crontab entries that say, eg,

*/5 * * * *     munin /usr/bin/munin-cron >& /dev/null

That terminal >& /dev/null is to tell cron to discard any output that is not otherwise handled by the executable/script being run.