Posts Tagged ‘cron’

Using ‘date’ in cron jobs

23. June 2009

I was trying to backup a file every hour by using crontab:

0 * * * * cp /project/myfile /project/backups/backup_`/bin/date +%Y-%m-%d-%H`
0 * * * * cp /project/myfile /project/backups/backup_$(/bin/date +%Y-%m-%d-%H)

None of these lines are working. Instead I receive mails, complaining about “unexpected EOF while looking for matching “” \ “syntax error: unexpected end of file”.
Referring to the man pages (man 5 crontab), “%” are “newline characters” and needs to be escaped with backslash:

The “sixth” field (the rest of the line) specifies the command to be run. The entire command portion of the line, up to a new-
line or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the crontab file. 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. There is no way to split a single command line onto multiple lines, like the
shell’s trailing “\”.

In other words, to get it working, add backslashes (\) in front of your “%”s and your fine:

0 * * * * cp /project/myfile /project/backups/backup_`/bin/date +\%Y-\%m-\%d-\%H`