記錄定時任務的一個錯誤:crontab 中使用"%"的問題

最近工做須要,須要定時執行命令文件,而且把執行的日誌重定向輸出到以日期命名的文件中,命令以下:shell

/bin/bash /data/shell/merge.sh &>> /data/shell/merge-`date +"%F"`.log 2>&1bash

單獨執行這條命令執行正常less

 

而後把命令添加到Linux的定時任務,天天凌晨02:30執行一次定時任務:crontab -lui

30 2 * * * /bin/bash /data/shell/merge.sh &>> /data/shell/merge-`date +"%F"`.log 2>&1翻譯

 

次日檢查發現定時任務執行失敗,查看日誌 /var/log/cron:rest

Feb 21 02:30:01 iZbp1cs0fu03n6k79ztuipZ CROND[27824]: (root) CMD (/bin/bash /data/shell/merge.sh &>> /data/shell/merge-`date +")日誌

從執行日誌發現cmd 從中間截斷了,命令沒有正常執行;crontab

 

結合輸出日誌發現錯誤日誌顯示了上面的腳本在 `date +" 以後就被截斷了,出現了語法錯誤。ip

查看manpage,發現這麼一句話:ci

The  "sixth" field (the rest of the line) specifies the command to be run.  

The entire command portion of the line, up to a new‐line or a "%" character, will be executed by /bin/sh or by the shell specified in the SHELL variable of  the  cronfile.   

A  "%" character  in  the command, unless escaped with a backslash (\), will be changed into newline characters, and all data after thefirst % will be sent to the command as standard input.

以後肯定原來是 % 這個符號在crontab裏面被翻譯成了命令結束,因此當crontab讀到%就吧後面的內容截取掉了,致使腳本執行失敗。 在%前面加上轉移符號"\"便可,以下

30 2 * * * /bin/bash /data/shell/merge.sh &>> /data/shell/merge-`date +"\%F"`.log 2>&1

檢查日誌看到定時任務執行成功:

Feb 22 02:30:01 iZbp1cs0fu03n6k79ztuipZ CROND[31285]: (root) CMD (/bin/bash /data/shell/merge.sh &>> /data/shell/merge-`date +"%F"`.log 2>&1)

相關文章
相關標籤/搜索