Wednesday, July 11, 2007

Properly setting up a crontab entry using 'date' to generate timestamps

I have a custom backup script that I want to run every night. I'd also like to have all the output (standard and error) redirected to a timestamped log file for subsequent review. My first stab at defining a cron job to handle this was something like the following:

00 0 * * * ~/bin/backup.sh > backup_$(date + %Y-%m-%d).log 2&>1

The only problem is it doesn't work!

Cron sends you messages pertaining to failed jobs in the system mail queue, which on Mac OS X you can access using the 'mailx' program, which comes with the system. Doing so, I saw this message:

/bin/sh: -c: line 1: unexpected EOF while looking for matching `)'

A little broswing the cron man pages turned up that "%" (as well as "#") is interpreted as a comment character. Looks like my timestamp generation was causing the job to fail. Grrr.

The solution? Escape each "%" with a backslash. The functional cron job definition is

00 0 * * * ~/bin/backup.sh > backup_$(date + \%Y-\%m-\%d).log 2&>1

Sanity restored.