我有一个从周一到周五运行的 crontab 作业,但我需要它对特定日期进行异常(exception)处理,例如 1 月 1 日、4 月 11 日等。
如何在我的 crontab 作业中异常(exception)?
* * * * 1-5 ./full-backup
最佳答案
最简单的方法是使用 and
或 or
列表序列。
man sh
: AND and OR lists are sequences of one of more pipelines separated by the&&
and||
control operators, respectively. AND and OR lists are executed with left associativity.An AND list has the form
command1 && command2
.command2
is executed if, and only if,command1
returns an exit status of zero.An OR list has the form
command1 || command2
.command2
is executed if and only ifcommand1
returns a non-zero exit status.
如果您想从 cron 中排除 2 天,比如说 1 月 1 日和 4 月 11 日,那么您可以执行以下操作:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
* * * * 1-5 [ `date '+\%m\%d'` == "0101" ] || [ `date '+\%m\%d'` == "0411" ] || ./full_backup.sh
从您有更多天数排除的那一刻起,它就变得有点棘手。您可以使用较小的脚本,例如 excludedaycmd
#!/usr/bin/env bash
while [[ $1 != "" ]]; do
[[ $(date "+%m%d" )) == $1 ]] && exit 1
shift
done
exit 0
如果该脚本的任何参数适合一天,则该脚本将以 1 退出。你的 cron 看起来就像这样。
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
* * * * 1-5 excludedaycmd 0101 0411 && ./full_backup.sh
任何其他脚本也可以以任何其他形式使用。
关于linux - Linux 的 crontab 天异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48818748/