Why percent signs (%) do not work in crontab? [duplicate]

瘦欲@ 提交于 2019-11-26 17:20:11

问题


I'm writing files out to a log ran by a bash script using cron. The call on cron looks like this:

*/25 * * * * bash script.sh > "/var/log/$(date +%Y-%m-%d_%H:%M).log"

But when I check the crontab it records as

*/25 * * * * bash script.sh > "/var/log/$(date +).log"

And it never writes the log file. Is there something I need to change to get cron to write the date?


回答1:


It is a matter of escaping variables:

* * * * * /usr/bin/touch /tmp/$(date +\%Y:\%m).log
#                                      ^   ^

worked to me.

From man 5 crontab:

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.

So

*/25 * * * * /bin/bash script.sh > "/var/log/$(date +\%Y-\%m-\%d_\%H:\%M).log"
#                                                    ^    ^   ^   ^   ^

should work.

Note I used /bin/bash instead of just bash.



来源:https://stackoverflow.com/questions/16238460/why-percent-signs-do-not-work-in-crontab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!