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/script.sh > /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/script.sh > /data/script_`date +\%y\%m\%d`.log 2>&1

, , , ,


  1. #1 by ice.simx on 15 Feb 2013 - 07:30

    thanx, it worked. Following were my modified crontab entries

    00,30 * * * * /path/runme.sh >> /log/$(date +”\%d\%m\%Y.log”) 2>&1

    🙂

  2. #2 by Eleanor on 03 Dec 2014 - 03:42

    Thank you guys

    I’v been annoied by this problem for a long time.
    After I sew this solution,I solved this problem.

    thank you very much

  3. #3 by KrustyHack on 18 Mar 2015 - 09:20

    hi,

    Thanks a lot ! It saves my day at work 🙂

  4. #4 by MiniMax on 09 Apr 2015 - 14:37

    Thanks a LOT !!! 😉

  5. #5 by Castro on 16 Oct 2017 - 16:16

    Thanks a lot !!!
    Muito obrigado. Ajudou muito…

  6. #6 by Ulf Christensen on 02 Jun 2018 - 11:14

    Found this today. It helped me to solve a problem that I had for a long time! Thanks a lot guys!

(will not be published)