crontab中的%具有特殊含义

引言

昨天在调试服务器的时候,发现设定的计划任务都没有执行!于是,通过各种方式来寻找原因:检查格式、查看权限、简单测试……一言以概之,经过漫长的折腾后终于找到了罪魁祸首——crontab命令字段中的百分号(%)!我在crontab的命令字段中都使用了$(date +%Y%m%d)的格式,其中的百分号(%)没有转义,导致命令无法正常运行。

正文

%(百分号)在crontab中是一个特殊字符,相当于回车,如果在命令(command)字段中包含%,那么只有第一个百分号前的文本才会包含在实际命令中,之后的内容将作为标准输入赋值给前面的命令。
如果命令行中需要%,必须得在%前面加一个反斜线()来转义,即“%”。

以上信息可以通过“man 5 crontab”查找到,原文如下:
The “sixth” field (the rest of the line) specifies the command to be run. The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the crontab file. 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. There is no way to split a single command line onto multiple lines, like the shell’s trailing “”.
译文如下:
第六个域(行的剩余部分)指明了要运行的命令。一行中整个命令部分遇到一个换行符或%结束,命令会以/bin/sh执行或以cron文件中 SHELL变量指明的shell执行。命令中的百分号(%) ,除非以反斜线() 转义,会被转换为换行符,第一个%后的所有数据会被发送给命令作为标准输入。

因此,如果crontab中含有类似”date +%Y%m%d“这样的内容的时候,记得一定要使用反斜线()进行转义!

    • vimrc中用”而非#表示注释;crontab中用%和换行符同时表示换行。不知道还有没有其他的例外……
      PS:也不知道这些例外是历史或程序原因造成的,还是软件作者故意这样做的。