I'm fairly new to cron and I'm trying to figure out a way to run a job every day of the week, except for the first day of each month and the first day of each week.
This may sound a little odd, but the context is that this is for a backup task. I want to backup every day, but also keep some backups around a little longer so take one backup each week and also one each month.
I want to setup a cron task for the daily job but I'm struggling to see how to effectively not run the daily task if it's on a day on which the weekly or monthly backup will also run. I think I can achieve this by adding a separate cron task for each day of the month, but that feels wrong because it's a lot of separate tasks.
Is there a better way to achieve this in cron?
I would schedule the job with a day-of-the-week restriction then prefix the actual job with a date
test for "day of the month". Use your own values for the hour & minute fields. The "day-of-the-month" field is *
, meaning run on any & all days of the month. The "month" field is also open. The "day of the week" field is restricted to Mondays through Saturdays, skipping the first day of the week (assuming you count Sunday as the first day of the week). If Monday is the first day of your week, use 0,2-6
as the "day of the week" value instead.
(minute) (hour) * * 1-6 [ $(date +\%e) -ne 1 ] && actual-job
The simplest approach (of restricting both the day-of-the-month and day-of-the-week fields) doesn't work, due to this Note in man 5 crontab
, with my bolded emphasis:
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,
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments