记录定时任务的一个错误:crontab 中使用"%"的问题

最近工作需要,需要定时执行命令文件,并且把执行的日志重定向输出到以日期命名的文件中,命令如下:

/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)

转载于:https://www.cnblogs.com/kofxxf/p/8456405.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值