Print date for the monday of the current week (in bash)

Viewed 43060

I want to get a date in the format 'YYYYMMdd' (for example, today would be 20110627) format for the monday of the current week. From tomorrow through to Sunday I'd like to still print out Mondays (today's) date. Then Next week, repeat the process

5 Answers

I think this actually answers what was requested:

date -d "next monday - 7 days"

If you want the monday previous to a given date, like a start of week function, there's a little more to it. That's what I was looking for when I searched up this question, so I'll add my answer here.

I tried to take a "reusable tool" approach.

My monday script:

#!/bin/bash
date=${1:-now}
shift
dow=`date +%u -d "$date"`
dow0=$[ $dow - 1 ]
date -d "$date -$dow0 days" "$@"

How it works:

  • get date -d argument from first command line argument, e.g. "2020-01-01 -2 weeks"
  • additional args are passed on to the final date command, e.g. to format with +%F
  • get the day of week with %u (1..7); 1 is Monday
  • subtract 1 as we want the range 0 to 6.
  • show the date for the given date, minus the "day of the week" offset

A similar sunday script, which turns out to be a little simpler:

#!/bin/bash
date=${1:-now}
shift
dow=`date +%w -d "$date"`
date -d "$date -$dow days" "$@"

Usage:

# monday 
Mon Aug 29 02:28:45 PM AEST 2022
# sunday now +%F
2022-08-28
# monday '2022-12-01' +%F
2022-11-28
Related