Crontab is a wonderful tool to run tasks at scheduled times. I noticed that my cron jobs fail if I use the percentage sign (%) in it. Why? It works if I just execute the command in my shell.
echo $(date +"%Y%m%d")
20180608
Ok, is the crontab using a different shell? Yes it is! Let’s try setting crontab to use the shell I want. This can be done by adding the path of my shell to it:
crontab -e
SHELL=/usr/local/bin/zsh
(Of course I could have switched to /bin/sh and executed the command from there)
Still no luck. Interesting…
Ok, let’s see what the manual says
Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.
Wait a minute, that’s it. I escaped all % signs and my crontab’s started to work, yay!
30 * * * * /usr/local/bin/iocage snapshot sql -n $(date +"\%Y\%m\%d")
This command creates ZFS snapshots of the jail called sql every hour at the 30th minute.
Lesson learned: % signs must be escaped in crontabs! For example if you specify date format in crontab add a \ in front of %.
Side note: one must use proper SQL backup tools, not just ZFS snapshots.