Using the % character in crontab entries

The % character is a special char for crontab entries, and in order to use it we have to escape it. For example a crontab entry like this:

1 0 * * * /bin/sleep `/usr/bin/expr $RANDOM % 600` ;
/usr/local/bin/mycommand

that attempts to run mycommand hourly with a random delay for the start, will fail because cron will see the % character and ignore the rest of the command; it will just run: /bin/sleep `/usr/bin/expr $RANDOM that will return a random number between 0-32767 and exit.

In order to have such a command running appropriately we will have to escape % and then it will run as expected:

1 0 * * * /bin/sleep `/usr/bin/expr $RANDOM \% 600` ;
/usr/local/bin/mycommand

(waiting for a random number smaller than 600 seconds, and then running mycommand).

This could be useful in various other situations and another example that comes to my mind at this time is to insert the date in some script output or parameters, like:

1 0 * * * mycommand >> /var/log/mylogs/`date +"\%Y\%m\%d"`.log

that will output the daily logs into a single, separate file.

comments powered by Disqus