Reputation: 7376
I want to loop and print end of month date between two dates.
I have below code but it prints day on day.
startdate='2021-01-01'
enddate='2021-04-01'
enddate=$( date -d "$enddate + 1 day" +%Y%m%d ) # rewrite in YYYYMMDD format
# and take last iteration into account
thedate=$( date -d "$startdate" +%Y%m%d )
while [ "$thedate" != "$enddate" ]; do
printf 'The date is "%s"\n' "$thedate"
thedate=$( date -d "$thedate + 1 days" +%Y%m%d ) # increment by one day
done
but I want these result for:
startdate='2021-01-01'
enddate='2021-04-01'
20210131
20210228
20210331
thanks in advance
Upvotes: 0
Views: 646
Reputation: 26452
Using date
command :
#!/usr/bin/env bash
startdate=$1
enddate=$2
while true; do
month_end=$(date -d "${startdate::6}01 +1month -1day" +%Y%m%d)
[[ $month_end -lt $enddate ]] && echo $month_end || break
startdate=$(date -d "$month_end +1day" +%Y%m%d)
done
Calling method
$ ./test.sh 20210101 20210401
20210131
20210228
20210331
Upvotes: 1
Reputation: 7277
Something like this
year=$(date +%Y)
for month in {01..04}; {
day=($(cal -d $year-$month))
echo "$year$month${day[@]:(-1)}"
}
20210131
20210228
20210331
20210430
or with -m flag
year=$(date +%Y)
for month in {01..04}; {
day=($(cal -m $month $year))
echo "$year$month${day[@]:(-1)}"
}
20210131
20210228
20210331
20210430
Upvotes: 2