7

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.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
teagles
  • 71
  • 1
  • 5
  • 2
    Did you try to escape it like `date +\%F` – gniourf_gniourf Apr 22 '14 at 20:43
  • Btw, this question would be more appropriate on another site, e.g., http://superuser.com/ or http://unix.stackexchange.com/ (hence the close requests). – gniourf_gniourf Apr 22 '14 at 20:46
  • Documented in the [crontab(5)](http://man.cx/crontab(5)) man page. – glenn jackman Apr 22 '14 at 21:04
  • `+\%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? – teagles Apr 22 '14 at 21:04
  • 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. – gniourf_gniourf Apr 22 '14 at 21:07
  • The [crontab tag wiki](http://stackoverflow.com/tags/crontab/info) actually says "There are several reasons for why a cron job wouldn't run as expected: 1. Using percent signs, as in date +%F" – that other guy Apr 22 '14 at 21:11

1 Answers1

13

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
Smar
  • 8,109
  • 3
  • 36
  • 48