Crontab 及其日志

Crontab and its logs

第一次写crontab

以下是时间和日期的结构

 # * * * * *  command to execute
 # │ │ │ │ │
 # │ │ │ │ │
 # │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
 # │ │ │ └────────── month (1 - 12)
 # │ │ └─────────────── day of month (1 - 31)
 # │ └──────────────────── hour (0 - 23)
 # └───────────────────────── min (0 - 59)

我输入如下

00 06     * /bin/sh /opt/cleanup.sh

觉得这不是woring

哪里可以看到crontab的日志??

您需要使用所有参数。所以要 运行 每天早上 6 点使用:

00 06 * * * /bin/sh /opt/cleanup.sh

您可能会在 /var/log/cron 中看到日志。

更多信息,您可以查看写得漂亮的部分Debugging crontab in [crontab] tag wiki

通常 cron 命令的输出会通过邮件 (man mail) 发送给所有者,但是当您执行 returns 输出(stdout 和 stderr)的代码时。当您登录时,您应该会看到类似 "There are new mails" 的内容。我不知道是否像您这样的错误 cron 计划(请参阅@fedorqui 的回复)会抛出错误日志。在任何情况下,要将计划的 cron 作业的输出和错误保存在文件中而不是邮件中,您可以像这样重定向输出:

00 06 * * * /bin/sh /opt/cleanup.sh > /where/you/have/write/permission/cleanup.log 2>&1

如果您想追加而不是覆盖,只需使用两个 >,如下所示:

00 06 * * * /bin/sh /opt/cleanup.sh >> /where/you/have/write/permission/cleanup.log 2>&1

要禁用日志,只需安排以下内容:

00 06 * * * /bin/sh /opt/cleanup.sh > /dev/null 2>&1

2>&1 表示 "redirect the channel 2 (error) to the pointer of channel 1 (standard output)"。标准输出被重定向到文件 (/my/file.sh > /my/file.log).