经常使用crontab定时备份文件,并在备份文件名中打上日期标签。例如备份和归档命令:

tar cjf foo-`date +%Y%m%d%H%M%S`.tar.bz2 foo

将这个命令写入crontab中,会发现命令不能如期执行。直觉判断应该是反引号的内容出问题。网上的资料“部分”验证了这个想法:原来crontab将百分号转义成换行符,分号后面的内容会被当做百分号前命令的标准输入。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 cronfile. 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.

解决办法

在百分号的前面加上反斜杠\转义。crontab中的写法为:

* * * * * root tar cjf foo-`date +\%Y\%m\%d\%H\%M\%S`.tar.bz2 foo

注意

问题由百分号引起,与反引号没关系。如果你觉得反引号的写法不好看,可以考虑用$方式执行命令:

* * * * * root tar cjf foo-$(date +\%Y\%m\%d\%H\%M\%S).tar.bz2 foo

使用$符号依然要转义百分号才能正常执行命令。

参考

  1. https://linux.die.net/man/5/crontab
  2. https://serverfault.com/questions/84430/whats-wrong-with-my-cronjob-syntax-im-trying-to-use-a-backtick