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" [email protected] < ~/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.

  • you're sending two inputs to 'mail -s` -- the (empty) output from the left side of the pipe and the redirected input from ~/job_fail.log
    – Jeff Schaller
    Oct 6, 2016 at 2:21

2 Answers 2


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:

[email protected]
[email protected]
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" [email protected] < ~/job_fail.log
  • 1
    Where you say 'ugly' I do not agree. I've ran into some tooling that returns proper error codes, but error output always on STDOUT. And this captures that properly ;)
    – GerardJP
    Oct 19, 2021 at 7:12
  • @GerardJP wrapper scripts (like "job_failure_test.sh") are for fixing tooling that fails to use standards. Oct 19, 2021 at 12:39

This feature is built into cron! If the command produces any output, or if it returns a nonzero status, then cron sends you an email.

Many modern distributions don't set up local email. If your doesn't, install a mail transfer agent (MTA). See e.g. this thread for Ubuntu, or Minimal MTA that delivers mail locally (for cron)? if you absolutely want something minimalistic. Or just install a common MTA such as Exim or Postfix and configure it for local delivery only (see e.g. this thread) for Debian. Once local email is set up, you can read your local email with your favorite mail client.

Instead of reading your email locally, you can create a file ~/.forward containing an external email address, and all your local email will be forwarded there. If you choose forwarding, you must have an MTA that's capable of sending mail externally (“smarthost”).

Alternatively, set the MAIL variable in the crontab to make it send the email directly to that address. This too requires that your system can send email externally.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .