[20200318]crontab檔案格式中的%.txt

lfree發表於2020-03-18

[20200318]crontab檔案格式中的%.txt

--//昨天寫一個定時執行程式,編輯crontab格式檔案.

# cat /etc/cron.d/dmesg
*/1 * * * * root /bin/date +"%Y/%m/%d \%T"  >> /dev/kmsg

--//多次嘗試不行,檢查/var/log/cron輸出,發現:
# grep "/bin/date" cron
Mar 17 10:41:01 xxxxxxxx crond[46790]: (root) CMD (/bin/date +")
Mar 17 10:44:01 xxxxxxxx crond[47015]: (root) CMD (/bin/date +')
Mar 17 10:45:01 xxxxxxxx crond[47141]: (root) CMD (/bin/date +\')
Mar 17 10:50:01 xxxxxxxx crond[48381]: (root) CMD (/bin/date  +'\'')
Mar 17 10:51:01 xxxxxxxx crond[49116]: (root) CMD (/bin/date   >> /dev/kmsg)
Mar 17 10:54:01 xxxxxxxx crond[49629]: (root) CMD (/bin/date +"%Y/%m/%d %T"  >> /dev/kmsg)

--//我開始以為引號"要轉義,加入後也不行.仔細看輸出發現截斷在%的位置,難道%在crontab格式檔案中很特殊嗎?

--//在crontab中%字元被認為是換行,所以你的命令中有%時,在crontab中要加\轉義.
$ 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  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.

--//補充今天上班觀察的情況:
# tdmesg  '' 20
2020-03-17 14:02:22: [7320889.130731] 2020/03/17 14:00:01
2020-03-17 15:02:15: [7324482.370652] 2020/03/17 15:00:01
2020-03-17 16:02:07: [7328074.614568] 2020/03/17 16:00:01
2020-03-17 17:01:59: [7331666.841731] 2020/03/17 17:00:01
2020-03-17 18:01:53: [7335260.087614] 2020/03/17 18:00:01
2020-03-17 19:01:45: [7338852.434101] 2020/03/17 19:00:01
2020-03-17 20:01:38: [7342445.701044] 2020/03/17 20:00:01
2020-03-17 21:01:30: [7346037.969419] 2020/03/17 21:00:01
2020-03-17 22:01:23: [7349630.185254] 2020/03/17 22:00:01
2020-03-17 23:01:16: [7353223.459631] 2020/03/17 23:00:01
2020-03-18 00:01:08: [7356815.831296] 2020/03/18 00:00:01
2020-03-18 01:01:01: [7360408.135095] 2020/03/18 01:00:01
2020-03-18 02:00:54: [7364001.414962] 2020/03/18 02:00:01
2020-03-18 03:00:46: [7367593.688400] 2020/03/18 03:00:01
2020-03-18 04:00:39: [7371186.932555] 2020/03/18 04:00:01
2020-03-18 05:00:32: [7374779.092577] 2020/03/18 05:00:01
2020-03-18 06:00:25: [7378372.338753] 2020/03/18 06:00:01
2020-03-18 07:00:17: [7381964.644293] 2020/03/18 07:00:01
2020-03-18 08:00:09: [7385556.914524] 2020/03/18 08:00:01
2020-03-18 09:00:03: [7389150.190761] 2020/03/18 09:00:01
--//你可以發現越偏移當前時間誤差更大。

--//最後改寫如下:
# cat /etc/cron.d/dmesg
0 * * * * root /bin/date +"\%Y/\%m/\%d \%T"  >> /dev/kmsg

--//另外發現以前定義別名zdate不好的地方,原來定義如下:
--//寫在檔案內容如下:
alias zdate="date +'%Y/%m/%d %T'"

--//顯示如下:
#  alias zdate
alias zdate='date +'\''%Y/%m/%d %T'\'''

--//單雙引號對調。
#  alias zdate='date +"%Y/%m/%d %T"'
#  alias zdate
alias zdate='date +"%Y/%m/%d %T"'

--//感覺這樣更好一些,沒有顯得這麼亂。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/267265/viewspace-2681048/,如需轉載,請註明出處,否則將追究法律責任。

相關文章