3

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
8

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 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 mean Saturday, 0 or 7 mean Sunday)

  • What if i extend the date range from 22-28 to 22-31? Because if have similar script for 3rd friday of every month with range 15-21 and -eq 5 and that works fine. – user3901666 Nov 7 '19 at 7:01
  • 2
    @user3901666, in interval 22-31 you may have more than one Saturday. Check your calendar for November this year. And for last Saturday its different because you can have 5 Saturdays in month – Romeo Ninov Nov 7 '19 at 7:10
  • I have the cron for last sunday of each month (posted in the description), But i don't know how its works. Can i modify it to get the cron for saturday? – user3901666 Nov 7 '19 at 7:19
  • The problem is I can't modify my script as it is a generic script which works for other schedules as well. – user3901666 Nov 7 '19 at 7:19
  • @user3901666, you can always create a copy of this script and edit it :) – Romeo Ninov Nov 7 '19 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.