Cron entry for last Saturday of every month

I want to schedule my script for last Saturday of every month.
I have come up with the below:

45 23 22-28 * *  test $(date +%u) -eq 6 && echo "4th Saturday"  && sh  /folder/script.sh

Is this correct or I need to change it?
I can’t test it right now as it will be invoked only on last saturday.
Please advise.

I have the below for last sunday of every month but i can’t understand much of it. The first part gives 24 which is sunday and after -eq gives 7 which i don’t know what it means:

00 17  * * 0 [ $(cal -s | tail -2 | awk '{print $1}') -eq $(date | awk '{print $3}') ] && /folder/script.sh

Can I modify the above to get last saturday?

With Romeo’s help I was help to come up with the below answer:

00 17 * * 6 [ $(cal -s | tail -2 | awk '{print $7}') -eq $(date | awk '{print $3}') ] && /folder/script.sh

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Your logic will not work. Month can have last Saturday to be on 29 or 30 or 31. For this reason the best way to do the check is to run it every Saturday and check in script if this is in last 7 days in month:

45 23 * * 6  sh  /folder/script.sh

and add in your script (here assuming the GNU implementation of date) something like:

if [ "$(date -d "+7 day" +%m)" -eq "$(date +%m)" ]
then echo "This is not one of last 7 days in month.";exit
fi
<rest of your script>

About your line in cron you should edit it to start like this:

00 17  * * 6

(6 means Saturday, 0 or 7 mean Sunday)

Method 2

If you happen to use the Dillon Crontab (which I believe it is better, includes more features, and supplies also anacron), then you have the option of:

If you specify both a day in the month and a day of week, it will be interpreted as the Nth such day in the month.

45 23 5 * 6  /path/script.sh

To request the last Monday, etc. in a month, ask for the “5th” one. This will always match the last Monday, etc., even if there are only four Mondays in the month

Hopefully you and others can use this answer for future consultation.


References:

Method 3

What about this:

45 23 */25,*/26,*/27,*/28,*/29,*/30,*/31 * SAT

I have not tried this, but Crontab Guru says it’s possible:

Cron entry for last Saturday of every month


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x