Posts Tagged date command

Using the ‘date’ command in your crontab

Crontab, as most people know, enables users to schedule commands or shell scripts to run periodically at certain times or dates.

The other day, this very useful Linux tool gave me a hard time! 🙁
Indeed, one of my commands wasn’t working in cron but was working perfectly fine when written in a shell console.

The faulty command looked like this:

0 5 * * 3 /data/ > /data/script_`date +%y%m%d`.log 2>&1

If I run this command in a shell console, everything works fine and I get a log file containing today’s date in its filename. However, if I set this command line in my crontab, it doesn’t work and no log file is even created!

Reading the documentation of cron, I discovered the following statement:

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.

Well, this is good to know, isn’t it? 😉
We need to escape the percent-signs on our command line.

So in order to get our ‘faulty’ command to run in cron, it needs to look like the following:

0 5 * * 3 /data/ > /data/script_`date +\%y\%m\%d`.log 2>&1

, , , ,