Crontab with a random sleep

June 3, 2011    crontab random sleep

Recently ran into this problem. We had a crontab entry that looked something like this

0 0 * * * /usr/bin/sleep $((RANDOM\%90)); cmdHere

What that attempted was to run a command a random amount of seconds once midnight hit. Now running the command on console causes it to error out

$  /usr/bin/sleep $((RANDOM\%90))
-bash: RANDOM\%90: syntax error: invalid arithmetic operator (error token is "\%90")

So what you might be saying is well the \ is messing it up so remove it. Well the problem is % is a reserved character in crontab land. It pretty much means ignore everything after it so you escape it. But its not working as expected. If you remove the \ from the shell command it works just fine.

So the real answer here was use expr. Once that was in all the crontab errors went away

0 0 * * * /bin/sleep `/usr/bin/expr $RANDOM \% 90`; cmdHere

comments powered by Disqus