1. 程式人生 > >記錄定時任務的一個錯誤:crontab 中使用"%"的問題

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

unless roo 記錄 翻譯 int 使用 tab 單獨 結束

最近工作需要,需要定時執行命令文件,並且把執行的日誌重定向輸出到以日期命名的文件中,命令如下:

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

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

然後把命令添加到Linux的定時任務,每天淩晨02:30執行一次定時任務:crontab -l

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

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

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

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

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

查看manpage,發現這麽一句話:

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)

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