Keeping Tabs on Cron

Cron

Email is a great way to keep track of automated tasks on servers you maintain, but it's not necessary to have scripts explicitly send email - you can keep a watch on cron jobs with cron's built-in email facility. This works with the standard Vixie cron used on GNU/Linux and the various BSD's. The way it works is that the standard output and standard error of any commands run will be emailed to the recipient(s) specified in the MAILTO environment variable. This variable is defined in the crontab file itself, as a single email address, or a comma-separated list of email addresses. If it is not defined, email is sent to the owner of the crontab. If it is set to empty (""), or no output is produced by a command, no email is sent. Here are examples showing the various ways this can work.

Capture All Output

Emails both STDOUT and STDERR of the command /usr/local/bin/backup.sh to doug@example.com.

MAILTO=doug@example.com 0 3 * * * /usr/local/bin/backup.sh

Capture No Output, Selectively

Discard both STDOUT and STDERR, effectively sending no email, even though MAILTO is defined. This is useful if you have several programs to run in the same crontab - you can selectively choose which will have their output captured and emailed.

MAILTO=doug@example.com 0 3 * * * /usr/local/bin/backup.sh > /dev/null 2>&1

Capture No Output, Never Send Email

Don't send an email at all, for any commands.

MAILTO="" 0 3 * * * /usr/local/bin/backup.sh

Capture All Output and Send Email to Crontab Owner

This just sends an email to the owner of the crontab, as no MAILTO is defined. I prefer to define MAILTO in all cases, since an undefined MAILTO is a common reason why system mailboxes fill with email - root's mailbox, for example. If such system mailboxes are not aliased, they will typically not be checked often (or at all).

0 3 * * * /usr/local/bin/backup.sh

Capture Error Output

Capture only STDERR by redirecting STDOUT to /dev/null. Since this is per-command, you can mix and match and have some commands that discard all output, and some that capture only STDOUT.

MAILTO=doug@example.com 0 3 * * * /usr/local/bin/backup.sh > /dev/null

Capture All Non-Error Output

Capture only STDOUT by redirecting STDERR to /dev/null.

MAILTO=doug@example.com 0 3 * * * /usr/local/bin/backup.sh 2> /dev/null

Sample Email

Here is what the email from cron will typically look like, notice the subject line contains the hostname, the program that was executed, and the user that executed it, so it can be filtered quite easily. A line like Starting backup... would have come from an echo statement inside the shell script.

Date: Sun, 6 May 2012 03:00:01 -0400 (EDT) From root@nix.example.com Sun May 6 09:00:05 2012 From: Cron Daemon To: doug@example.com Subject: Cron /usr/local/bin/backup.sh Starting backup... First line of output Next line of output Backup complete...

More Reading