2

I want to specify a range of time and count the weekdays within this range in bash. I found this snipped and edited it to print January and February in 2020:

#!/bin/bash

startdate=2020-01-01
enddate=2020-02-28

curr="$startdate"
while true; do
    echo "$curr"
    [ "$curr" \< "$enddate" ] || break
    curr=$( date +%Y-%m-%d --date "$curr +1 day" )
done

Now I only want to print all Mondays within this range, how can I do this?

I though of replacing echo "$curr" by something like: echo "$curr" | date +%Y-%m-%d-%a or without echo like: date +%Y-%m-%d-%a <<< "$curr" to add the weekdays to the output with %a and then filter the Mondays with sed or awk and count them. Though my approach of formatting the output this way does not work.

1 Answer 1

2

How about

startdate=2020-01-01
enddate=2020-02-28
mondays=()
# what day of week is startdate? Sun=0, Sat=6
dow=$(date -d "$startdate" "+%w")
# the date of the first monday on or after startdate
# if you want Tuesdays, change "1" to "2", and so on for other days.
monday=$(date -d "$startdate + $(( (7 + 1 - dow) % 7 )) days" "+%F")
# find all mondays in range
until [[ $monday > $enddate ]]; do
    mondays+=( "$monday" )
    monday=$(date -d "$monday + 7 days" "+%F")
done
printf "%s\n" "${mondays[@]}"

outputs

2020-01-06
2020-01-13
2020-01-20
2020-01-27
2020-02-03
2020-02-10
2020-02-17
2020-02-24
3
  • awesome, THXAL! Commented Jun 20, 2019 at 22:01
  • what is the mondays=() for? Commented Jun 20, 2019 at 22:05
  • 1
    @nath: That declares the mondays array and ensures it is empty for its use later in the code. Commented Jun 20, 2019 at 22:06

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.