Skip to content

Instantly share code, notes, and snippets.

@bbinet
Created September 27, 2017 07:40
Show Gist options
  • Save bbinet/57b941084b5d30626bba0c789a4eecab to your computer and use it in GitHub Desktop.
Save bbinet/57b941084b5d30626bba0c789a4eecab to your computer and use it in GitHub Desktop.
Get dates for Nth weekday in month: eg. get every 3rd tuesday of next 12 months
#!/bin/bash
if [ $# -lt 2 ]
then
echo "Usage: $0 <day_in_week> <week_in_month> [<nb_months>]"
echo " day_in_week: [0-6] (Sun=0 Mon=1 Tue=2 Wed=3 Thu=4 Fri=5 Sat=6)"
echo " week_in_month: [1-5]"
fi
day_in_week=$1
week_in_month=$2
nb_months=${3:-12}
nb_days=$(($nb_months * 31))
d0=$(date +"%Y%m01")
_m=""
i=0
while [ $i -le $nb_days ]
do
read -r w m d < <(date -d"$d0 $i day" +"%w %m %d/%m/%Y")
if [ "$m" != "$_m" ]
then
_m="$m"
_cnt=0
fi
if [ "$w" == "$day_in_week" ]
then
_cnt=$(($_cnt + 1))
if [ "$_cnt" == "$week_in_month" ]
then
echo $d
fi
i=$(($i + 7))
else
i=$(($i + 1))
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment