anandketki
anandketki

Reputation: 31

How to get last sunday's date from today's date using shell script?

I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date. I tried this,

a=`date -dlast-sunday +%Y%m%d`

but this gives a date of Sunday before the last one.

Upvotes: 3

Views: 2450

Answers (4)

Gopika BG
Gopika BG

Reputation: 817

The command to print the date of last Sunday by taking today's date is :

a=$(date -d 'last Sunday ' +"%A %F")
echo $a

Upvotes: 1

chepner
chepner

Reputation: 531075

Instead of asking for last Sunday, ask for one week before next Sunday.

$ date +%Y%m%d
20190531
$ date -d'next sunday - 1 week' +%Y%m%d
20190526

Just as "last Sunday" is always earlier than the current day, so is "next Sunday" always after the current day.

As it is Friday as I write this answer, let's ask for last Friday using this technique:

$ date +"%A %F"
Friday 2019-05-31
$ date -d 'next Friday - 1 week' +"%A %F"
Friday 2019-05-31

Upvotes: 9

David C. Rankin
David C. Rankin

Reputation: 84551

You can do that simply with the date command itself using the date -d option where:

date -d "today - $(date -d today +"%u") days"

Where you would pass whatever date you like as today (which is used as an example) and it will give the date of the previous Sunday. It does so by subtracting the current day of the week (date -d today +"%u") number of days from the given date (today in the example). You can use an if before checking if [ "$(date -d today +"%u")" -eq '7' ]; then date; else ... fi to simply output the current date if today is Sunday.

Example

$ date -d "today - $(date -d today +"%u") days"
Sun May 26 23:04:44 CDT 2019

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following.

cal |
awk -v dat=$(date +%d) '
{
  for(i=1;i<=NF;i++){
    if($i==dat){
      if(i!=1){
         print "Last Sunday is: "$1
      }
      else{
         print "This day itself is Sunday."
      }
    }
  }
}'

Upvotes: 1

Related Questions