Having cron troubles with percent (%) signs in crontabs?

I recently wrote a cronjob which would save off my Ubuntu home server's current packages list every night to a dated file so that I have a history of the changes that I've made to my system. The entry in my crontab looked something like this:

# package lists (5am)
0 5 * * * dpkg -l > /var/log/packages/`date +%F`.txt
After a couple of days I decided to take a look at the files generated so far but to my disappointment I found none. After a quick search for dpkg in /var/log I found my problem reported in syslog:
... /USR/SBIN/CRON[28508]: ... CMD (dpkg -l > /var/log/packages/`date +)
I noticed that the command recorded to the logs was up to '`date +' - the next character - the percent sign (%) - was causing some kind of issue. A quick search threw up the Wikipedia page for Crontab which mentioned:
Another common mistake is to use unescaped % in your command; you have to escape them
All I had to do was change % to be \%. My working crontab entry now looks like this:
# package lists (5am)
0 5 * * * dpkg -l > /var/log/packages/`date +\%F`.txt
The funny thing was that most of the 'proper' Linux documentation for cron and crontab do not mention anything about percent signs (%) - I'm finding that I'm going to Wikipedia for answers more and more these days...

Technorati Tags: , , , ,

2 comments:

Stefan Lasiewski said...

I ran into the same problem. The documentation for SuSE 9.2, Centos 4.x & RedHat 4.x do mention this:

Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.


Of course, now if I want to cut & paste the crontab command to the commandline, I end up with a fugly logfile:

/var/tmp/logfile.\2007\09\10

Bah! A dozen commandline programs use '%' as a placeholder. Why can't cron play nicely!

abeacock said...

Now that is a nice looking command line... ;)