Curating cron emails

As you might know, cron captures all the output of executed tasks and mails them to the user under which the tasks are executed. The problem is that often this mail just piles up somewhere in /var/mail directory, without being ever reviewed. It’s not a good practice, akin to sweeping the trash under the carpet.

The good practice is:

  1. Use a separate log file for each cron task.
  2. Redirect all output to the log, and additionally print stderr to terminal:
    exec 3>&1
    exec > >(tee -a ${LOGFILE} >/dev/null) 2> >(tee -a ${LOGFILE} >&3)
  3. Capture all that mail and one by one work out all the quirks in your scripts.

Capturing is usually done with something like “root: [email protected]” in /etc/aliases. However, it’s error prone, as various packages add their own accounts and that mail won’t go to root. Manually adding entries is also subject to human errors. So what we’re looking for is wildcard match. Unfortunately, that is not trivial with some email servers. I suggest you do yourself a favor and install Exim, instead of Sendmail or Postfix.

In Exim config (/etc/exim/exim.conf or RedHat based distros, /etc/exim4/exim4.conf.template on Debian based) find system_aliases stanza, and make the change:

-data = ${lookup{$local_part}lsearch{/etc/aliases}}
+data = ${lookup{$local_part}wildlsearch{/etc/aliases}}

Then, add wildcard to /etc/aliases:

*: [email protected]

Restart Exim, and prepare for polishing your cronjobs.

Unfortunately, even with this, cron tasks are still prone to various issues, so for important jobs it’s better to use something more reliable. (But you should capture cron emails, still. They often point out non-obvious issues.)