crontab里的特殊符號%導致命令不能執行


有群里的小伙伴說crontab里的任務不執行,具體是這樣的

*/1 * * * * /bin/date "+%Y-%m-%d %H:%M:%S" >>/data/tmp/test.log

我試了下在命令行可以執行,定時任務確實不執行,於是去翻了下日志:

#tail -f /var/spool/mail/root
X-Cron-Env: <HOME=/root>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=root>
X-Cron-Env: <USER=root>
Message-Id: <20200108081701.8FD502100481@D3L40.localdomain>
Date: Wed,  8 Jan 2020 16:17:01 +0800 (CST)

/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/bin/sh: -c: line 1: syntax error: unexpected end of file

From root@D3L40.localdomain  Wed Jan  8 16:18:01 2020

說是語法錯誤,結尾不對,明明是兩個雙引號啊,這樣就有可能是里面有特殊字符導致命令意外中斷了,於是查了下萬能的百度發現:

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 “”.

大概是在crontab里%當換行符用了,想要正常使用就得加反引號\,\%這樣來用。

於是把命令改成了:

*/1 * * * * /bin/date "+\%Y-\%m-\%d \%H:\%M:\%S" >>/data/tmp/test.log

最后:

# cat test.log
2020-01-08 16:38:01
2020-01-08 16:39:01

可以了,於是想着記一下,好記性不如爛筆頭嘛。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM