Friday, April 4, 2008

Cron Doesn't Read Minds: Customizing My Crontab

Some mistakes I make over and over again.

In part, I automate so I can fix stuff once -- so I don't have to smack my forehead and say, "I knew that."

I (all too) often forget that cron jobs don't have my environment, and may not even have my shell or my email address.

I solve this with a template crontab header. My crontabs start like this:
     $ crontab -l
     ## my crontab

     SHELL=/bin/bash
     PATH=/bin:/usr/bin:~/bin
     BASH_ENV=/home/jsh/.bash_env
     MAILTO=jeffrey.haemer+crontab@gmail.com

     # minute (0-59)
     # |      hour (0-23)
     # |      |      day of the month (1-31)
     # |      |      |    month of the year (jan-dec)
     # |      |      |    |     day of the week (sun-mon, with 0=sun)
     # |      |      |    |     |        command
     # |      |      |    |     |        |
     #
       0     23      *    *     *        crontab -l > ~/bin/crontab.txt 2>/dev/null
       ...
The column indicators are good reminders and visual indicators of what goes where.

Here's what the variable settings give me:

$SHELL ensures I won't use cron's default: /bin/sh
$PATH means I won't accidentally get command versions I don't want.

My .bash_env is typically a link to .bashrc. Bash sources $BASH_ENV at
startup when it's a non-interactive, non-login shell, so I get all the stuff I come to assume.

$MAILTO says where to send me error messages. I use gmail's plus addressing so I can search for my cron-job errors when I have to. I put this into root's crontabs on my boxes, too, so errors won't go to root's mailbox, which I never read.

No comments: