Run script on every last sunday of the month

Hi ALL,

I have been testing this script to run for every last Sunday of the month,looks like month which have 5 sunday (july 2016 )is not passing this and failing every time.

Here is what I am using,

current_date=31
        echo " CURRENT DAY -> $current_date"

        if [ $current_date -le 7 ]
        then
                week=A
        else
                if [ $current_date -gt 7 ] && [ $current_date -le 14 ];
                then
                        week=B
                else
                        if [ $current_date -gt 14 ] && [ $current_date -le 21 ];
                        then
                                week=C
                        else
                                if [ $current_date -gt 21 ] && [ $current_date -le 28 ] ;
                                then
                                        week=D
                                else
                                        week=E
                                fi
                        fi
                fi
        fi
        echo "CURRENT WEEK --> $week"
        echo ""

WEEK is a variable which I am passing with the script.

ksh test_script.sh D

Any clue will be highly appreciated.Thanks again for your time.

ls=$(cal | awk '$1+=0 {ls=$1} END {print ls}')
ts=$(date +"%d")

[[ $ls = $ts ]] && echo "today is the last sunday of the month"
2 Likes

Hi netdbaind,
The problem with your logic is that the last Sunday in a month is 22-28 in a month with 28 days, 23-29 in a month with 29 days, 24-30 in a month with 30 days and 25-31 in a month with 31 days. There is nothing that you have shown us in your code that determines whether or not you are in a leap year nor what month you're evaluating.

The code rdrtx1 suggested works in any locale where cal will print Sundays as the leftmost field on a line. You could guarantee that the output from cal will give you what you want no matter where in the world you run it if you change the first line to:

ls=$(LC_ALL=C cal | awk '$1+=0 {ls=$1} END {print ls}')
1 Like