crontab中的%特殊性如何?

Jua*_*blo 19 bash crontab

在crontab中,你可以这样做吗?

* * * * * echo $( date +%F) >> /path/date.txt
Run Code Online (Sandbox Code Playgroud)

bmk*_*bmk 32

你的crontab行的实际问题不是$()或反引号.问题是百分号%.它在crontabs中具有特殊含义.

从联机帮助页:

...
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.
...
Run Code Online (Sandbox Code Playgroud)

如果你使用\它来转义百分号,它应该按预期工作:

* * * * * echo $(date +\%F) >> /tmp/date.txt
Run Code Online (Sandbox Code Playgroud)

要么

* * * * * echo `date +\%F` >> /tmp/date2.txt
Run Code Online (Sandbox Code Playgroud)

都在我的网站上工作.

  • 请注意,反斜杠会传递给shell.所以像上面那样的命令会起作用,因为shell会删除反斜杠,但是字符串中的反斜杠会被shell留下,例如http://www.hcidata.info/crontab.htm (2认同)
  • 我非常讨厌 cron (2认同)