Naveenan Naveenan - 2 months ago 29
Linux Question

Bash- getting week start from date

I am trying to create a bash variable in a single line code that subtracts one day from current day and then get date of Monday of the subtracted day. How do I do this in a single line.

I tried:

date --date="1 days ago" -d "last monday"

But this option but this gets the last monday first and subtract one day. I want to subtract one day and then get last monday.

Answer Source


$ date -d "$(date -d yesterday +%u) days ago"
Mon Aug 21 18:18:54 PDT 2017

How it works:

  • date -d yesterday +%u gets yesterday's day of the week (1=Monday, 7=Sunday).

  • date -d "$(date -d yesterday +%u) days ago" returns the date for enough days ago to get the monday before yesterday.

    For example, since today is Sunday, yesterday's day of week is 6 (Saturday). 6 days ago is last monday.

    If today was Monday, yesterday's day of the week would be Sunday which is 7 and "7 days ago" would be the monday before today.