Pages

Thursday, 6 February 2020

When "crontab" meets "date"

Look at the following cron job.

$ crontab -l
* * * * * date +%Y%m%d%H%M%S

This job actually does not print anything. The reason is crontab will eat everything after the first %.

$ man 5 crontab
....
The "sixth" field (the rest of the line) specifies the command to be run.  The entire command portion of the line, up to a newline or a "%" character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile.  A "%" character in the command, unless escaped with a backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.

Based on the above info, actually, the command run by crond becomes:

echo Y%m%d%H%M%S | date +

The solution is obvious, just to escape the '%'.

crontab -l
* * * * * date +\%Y\%m\%d\%H\%M\%S

No comments:

Post a Comment