Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special escaping for crontab

I have the following user crontab entry on a RHEL 6 machine (sensitive values have been replaced):

[email protected]
0 5 * * * ~/bin/app_state.sh host-arg 9200 > ~/state/app-state-$(hostname)-$(date +%F).json

Which produces this entry in /var/log/cron:

Apr 23 05:00:08 host CROND[13901]: (dbjobs) CMD (~/bin/app_state.sh host-arg 9200 > ~/state/app-state-$(hostname)-$(date +)

But no file.

After changing the statement to:

43 5 * * * ~/bin/app_state.sh host-arg 9200 > ~/state/app-state-static.json

I get a better log entry and the file is created at ~/state/app-state-static.json

I'm sure there's some issue with not escaping the +%F but can't for the life of me find details of how I should be escaping it. I could wrap the filename generation inside another shell script but this is more easy to read for people coming looking for the file.

like image 751
teagles Avatar asked Apr 22 '14 20:04

teagles


1 Answers

As crontab tag wiki says, percent characters are problematic in crontabs; % gets converted to a newline:

[..] > ~/state/app-state-$(hostname)-$(date +%F).json

would run command as

[..] > ~/state/app-state-$(hostname)-$(date +\nF).json

“Escaping” percent characters is possible, but the escape character gets executed in the command. A job like following would run the command with \ in front of percent character.

0 5 * * * ~/bin/app_state.sh host-arg 9200 > ~/state/app-state-$(hostname)-$(date +%F).json

One way to circumvent this problem is to have the command in a script and execute that as a cron job:

/usr/local/bin/app_state_cron.sh:

#!/bin/sh

~/bin/app_state.sh host-arg 9200 > ~/state/app-state-$(hostname)-$(date +%F).json

And in crontab:

0 5 * * * /bin/sh /usr/local/bin/app_state_cron.sh
like image 63
Smar Avatar answered Sep 19 '22 01:09

Smar