您可以每天运行它,但使用 date +%w 打印日期编号并采取不同的行动(调用 > 来破坏文件而不是 >> 来追加)。
请注意,某些 cron 守护进程需要对 % 进行转义,因此需要对 \% 进行转义。
# Run every day at 00:30 but overwrite file on Mondays; append every other day.
# Note that this requires bash as your shell.
# May need to override with SHELL=/bin/bash
30 00 * * * if [ "$(date +\%w)" = "1" ]; then /your/command > /your/logfile; else /your/command >> /your/logfile; fi
编辑:
您在上面的 cmets 中提到您的实际目标是日志轮换。
Linux 系统的规范是使用logrotate 之类的东西来管理这样的日志。这还有一个好处是您可以保留多个以前的日志文件并根据需要对其进行压缩。
我建议使用 logrotate config sn-p 来实现您的目标,而不是在 cron 作业本身中执行它。如果只是为了日志轮换,将它放在 cron 作业中是违反直觉的。
这是一个示例 logrotate sn-p,它可能位于 /etc/logrotate.d/yourapp 之类的位置,具体取决于您使用的 Linux 发行版。
/var/log/yourlog {
daily
missingok
# keep one year of logs
rotate 365
compress
# keep the first one uncompressed for ease of viewing
delaycompress
}
这将导致您的日志文件每天轮换,第一次迭代类似于/var/log/yourlog.1,然后压缩迭代,例如/var/log/yourlog.2.gz、/var/log/yourlog.3.gz 等等。
因此,在我看来,您的问题实际上不是 cron 问题。上面使用的这种 cron 技巧只适用于以下情况,例如当您希望在每月的最后一个星期日或每月的最后一天触发作业,或其他无法用 cron 语法表达的条件时.