Special escaping for crontab [duplicate]
Asked Answered
K

1

11

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.

Kamal answered 22/4, 2014 at 20:36 Comment(6)
Did you try to escape it like date +\%FFlickertail
Btw, this question would be more appropriate on another site, e.g., superuser.com or unix.stackexchange.com (hence the close requests).Flickertail
Documented in the crontab(5) man page.Sofar
+\%F did the trick. I'll re ask on unix stack exchange so the answer can go on record but is there a clean way to close it out here?Kamal
Now that you have your answer it's useless to ask it on another site (especially this might be a FAQ so your question might be tagged as duplicate). Just leave everything as it is! prosperity will tell.Flickertail
The crontab tag wiki actually says "There are several reasons for why a cron job wouldn't run as expected: 1. Using percent signs, as in date +%F"Wolenik
D
15

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
Declarative answered 27/8, 2019 at 7:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.