Linux – How to make cron send email with error log when script throws errors

cronio-redirectionlinuxmailxpipe

I have a cron job that runs a script that writes checks for errors in an sql database and writes the errors to a log file. The log file is supplied in the command to run the script. I only want to receive an email when the script finds errors, and I want the log to be included in the email. I don't want to receive an email if the script doesn't find any errors. Apparently the script writes to the log when the script both finds or does not find errors (I didn't write this script).

    20 6-10 * * 1-5 ~/job_failure_test.sh -o ~/job_fail.log 2>&1 /dev/null | mail -s "Errors" myemail@something.com < ~/job_fail.log

So far this line sends me emails when there are errors written to the log, but it doesn't send me the updated log. It sends me the log from the previous execution of the cron job.

Best Answer

Just change | (a pipe) to || (an or) (assuming the script uses exit codes properly) though changing the script to only output on error and doing this is better practice:

MAILFROM=myemail@something.com
MAILTO=myemail@something.com
20 6-10 * * 1-5 ~/job_failure_test.sh

The ugly way;

20 6-10 * * 1-5 ~/job_failure_test.sh > ~/job_fail.log 2>&1 || mail -s "Errors" myemail@something.com < ~/job_fail.log
Related Question