Using date in a cronjob (and solve error grandchild failed error)

Written by - 0 comments

Published on - last updated on April 29th 2022 - Listed in Linux Shell


In some cases it makes sense to run a cronjob with an output file containing the current date (e.g. a backup file).
In my case I needed to get the content of a website every 30 minutes and save the content to an output file.

Here's my crontab entry:

30 * * * * wget http://www.example.com/myscript.php -O /tmp/output-$(date +%Y%m%d%H%M).out

Unfortunately that didn't work and resulted in the following error (seen in /var/log/cron.log):

/USR/SBIN/CRON[28734]: (web0) CMD (wget http://www.example.com/myscript.php -O /tmp/output-$(date +)
/USR/SBIN/CRON[28730]: (CRON) error (grandchild #28734 failed with exit status 1)

The interesting part here is that the date format (+%Y%m%d%H%M) is not shown in the log entry. Why's that?

On my research I came across a very interesting article (http://www.alleft.com/sysadmin/common-cron-mistakes), which basically reminded me of the following importance:

The first important observation about the crontab file is this: It’s not a shell script.

Facepalm. Of course! I got too used to create a shell script and then execute this shell script in the crontab. Here I want the final commands directly launched from cron.
In the same article an important information is also given, that percentage signs (%) need to be escaped in a crontab file. Let's verify this.

First a standard echo of the current year:

01 * * * * /bin/echo $(/bin/date '+%Y') >> /tmp/test.log

This failed - actually not a big surprise because I ddin't escape the percentage sign:

/USR/SBIN/CRON[30113]: (root) CMD (/bin/echo $(/bin/date '+)
/USR/SBIN/CRON[30112]: (CRON) error (grandchild #30113 failed with exit status 1)

 Now let's try the same with the escaped percentage:

02 * * * * /bin/echo $(/bin/date '+\%Y') >> /tmp/test.log

/usr/sbin/cron[1924]: (root) RELOAD (crontabs/root)
/USR/SBIN/CRON[30205]: (root) CMD (/bin/echo $(/bin/date '+%Y') >> /tmp/test.log)

That looks much better! Let's verify the output:

cat /root/log/test.log
2013

Success! Let's hope that having written it down now will remind me quicker next time.


Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.