Linux crontab for nth Satuday of the month

旧巷老猫 提交于 2020-01-16 03:28:07

问题


I like to run back up for all weekdays except Saturday. My crontab entry

30 16 * * 1,2,3,4,5 ./backup.sh

This entry working fine. Also, I like to take back up on 1st, 3rd Saturday. If any 5th Sutarday available in a month then the back up should run. What will be the entry for crontab? I am guessing

30 16 1-7, 15-21, 29-31 * 6 ./backup.sh

Am I right?


回答1:


Am I right?

No you are not correct. The crontab manual states:

Note: The day of a command's execution can be specified in the following two fields day of month, and day of week. If both fields are restricted (i.e., do not contain the "*" character), the command will be run when either field matches the current time. For example, 30 4 1,15 * 5 would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.

So how can we do it?

If you want to determine which Saturday of the month it is, i.e. whether it is the 1st, 2nd or 3rd Saturday of the month, all you have to do is look at the weekday of the Saturday and do the following integer computation:

D=$(date "+%d")
echo $(( (D-1)/7 + 1 ))

This value will return the corresponding number. This does not only work for Saturdays but for any Weekday.

Since the OP wants the cron to work on the 1st, 3rd and potentially the 5th Saturday, it actually states that the cron runs on every odd-numbered Saturday:

D=$(date "+%d")
echo $(( ((D-1)/7 + 1) % 2 ))

Using this as an additional test, allows us to write the cron as:

# Example of job definition:
# .---------------- 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

 30 16  *  *  6   (( (($(date "+\%d") - 1)/7 + 1) % 2 == 1 )) && command


来源:https://stackoverflow.com/questions/55430509/linux-crontab-for-nth-satuday-of-the-month

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!