How to find date of last Sunday of month using date command on Linux or Unix

date

#1

How to find Date for Last to last Sunday ?


#2

Try using cal command:

cal nov 2018
cal dec 2018

Outputs:

   December 2018      
Su Mo Tu We Th Fr Sa  
                   1  
 2  3  4  5  6  7  8  
 9 10 11 12 13 14 15  
16 17 18 19 20 21 22  
23 24 25 26 27 28 29  
30 31  

Now use the awk to find grab all dates from 1st column

cal dec 2018 | awk '/^ *[0-9]/{ print $1}' 

So you get:

1
2
9
16
23
30

Just grab the last value:

cal dec 2018 | awk '/^ *[0-9]/{ print $1}'  | tail -1

Sample outputs:

30

Try few examples:

for m in {1..12}
do 
  sundate=$(cal $m 2018 | awk '/^ *[0-9]/{ print $1}' | tail -1)
  echo "Last Sunday of $m/2018 is $sundate"
done

Outputs:

Last Sunday of 1/2018 is 28
Last Sunday of 2/2018 is 25
Last Sunday of 3/2018 is 25
Last Sunday of 4/2018 is 29
Last Sunday of 5/2018 is 27
Last Sunday of 6/2018 is 24
Last Sunday of 7/2018 is 29
Last Sunday of 8/2018 is 26
Last Sunday of 9/2018 is 30
Last Sunday of 10/2018 is 28
Last Sunday of 11/2018 is 25
Last Sunday of 12/2018 is 30