Special escaping for crontab

bash, cron, rhel

Solution

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

Problem

I have the following user crontab entry on a RHEL 6 machine (sensitive values have been replaced): ``` MAILTO=cron-errors@organisation.com 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.

Original source

Related problems