[20200318]crontab文件格式中的%.txt

[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"'

--//感觉这样更好一些,没有显得这么乱。

请使用浏览器的分享功能分享到微信等