[ale] First three Fridays of a month via a Bash script?

JD jdp at algoloma.com
Wed Jun 6 12:31:01 EDT 2012


On 06/06/2012 10:46 AM, James Sumners wrote:
> I've been thinking on this one since yesterday and haven't come up
> with anything. I have a Bash script that I want to run on the first
> three Fridays of every month. I don't think I can setup such a weird
> schedule in Cron, so I'm thinking of just running it every Friday and
> the script will exit without doing anything if it isn't an appropriate
> day.
> 
> My preference is to stick with standard utilities and Bash without
> resorting to something like Python. The problem I'm encountering is
> that GNU date does relative calculations either from the current
> system time or from a file's modification time. This means I can't use
> a contrived date such as the first of every month to do something like
> `date -d 'first Fridate'`, `date -d 'second Friday'`, and `date -d
> 'third Friday'` because I can't supply two '-d' parameters (one for
> the start date and a second for the desired calculation).
> 
> So, does anyone have any suggestions on how I can do this?

Actually, I think you can run this from cron.

The boundary conditions are when the 1st of the month is on a Friday, like June
2012 and again when the 1st of the month is on a Saturday, like Sept 2012.  The
3rd Friday will never happen after 21st - so any Friday before the 22nd of the
month is in your range of 1st, 2nd, 3rd Friday.

How would a crontab be written to achieve that?

# .---------------- 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
0 4 1-21 * 5 /path/to/command

Run at 4am, right?

Well, according to the man page ... I'm wrong.  That would run every day from
1-21 AND every Friday - not what we want.  The best answer leveraging cron is to
either
a) run the command either every day less than 22 and return for non-Fridays
or
b) run only on Fridays, but if the day-of-the-month is over 21, return.

I'd be inclined to use method "b", but I'd document it all over the place.


More information about the Ale mailing list