为什么crontab脚本不起作用?

通常情况下,crontab脚本不能按计划或按预期执行。这有许多原因。

1.错误的crontab符号 2.权限问题 3.环境变量

这个社区维基旨在汇总 "crontab "脚本未按预期执行的首要原因。请将每个原因写在一个单独的答案中。

请在每个答案中包括一个原因--关于为什么不执行的细节--以及对该原因的修复。

请只写针对cron的问题,例如,在shell中按预期执行的命令,但在cron中却错误地执行。

我的首要问题:如果你忘记在crontab文件的结尾添加换行。换句话说,crontab文件应该以一个空行结束。

下面是关于这个问题的手册中的相关章节(man crontab然后跳到最后)。

   Although cron requires that each entry in a crontab end  in  a  newline
   character,  neither the crontab command nor the cron daemon will detect
   this error. Instead, the crontab will appear to load normally. However,
   the  command  will  never  run.  The best choice is to ensure that your
   crontab has a blank line at the end.

   4th Berkeley Distribution      29 December 1993               CRONTAB(1)
评论(12)

脚本应使用绝对路径。

例如,应该使用/bin/grep而不是grep

# m h  dom mon dow   command
0 0 *  *  *  /bin/grep ERROR /home/adam/run.log &> /tmp/errors

而不是。

# m h  dom mon dow   command
0 0 *  *  *  grep ERROR /home/adam/run.log &> /tmp/errors

这一点特别棘手,因为同样的命令在从shell执行时也会起作用。原因是cron没有和用户一样的PATH环境变量。

评论(3)

Cron正在调用一个不可执行的脚本。

通过运行chmod +x /path/to/scrip,该脚本变得可执行,应该可以解决这个问题。

评论(2)