I am trying to loop through last 25 months, but my command is skipping Feb and duplicating March
Command
for i in {00..25}; do for ym in $(date -d "-$i month" %Y-%m); do echo ${ym}; done; done
Output
2022-04
2022-03
2022-03 --this needs to be Feb
2022-01
2021-12
2021-11
2021-10
2021-09
2021-08
2021-07
2021-06
2021-05
2021-04
2021-03
2021-03 --this needs to be Feb
2021-01
2020-12
2020-11
2020-10
2020-09
2020-08
2020-07
2020-06
2020-05
2020-04
2020-03
How do I modify it so it works as intended?
CodePudding user response:
Following my comment:
$ date -ud '2022-04-29 -2 month'
Tue Mar 1 00:00:00 UTC 2022
The need is to "pin" the day so that it's valid for all months (disregarding whatever is the "current day")
this_month=$(date -u ' %Y-%m-01') # the first day of this month
for i in {0..25}; do date -ud "$this_month -$i month" ' %Y-%m'; done
outputs
2022-04
2022-03
2022-02 <<<
2022-01
2021-12
2021-11
2021-10
2021-09
2021-08
2021-07
2021-06
2021-05
2021-04
2021-03
2021-02 <<<
2021-01
2020-12
2020-11
2020-10
2020-09
2020-08
2020-07
2020-06
2020-05
2020-04
2020-03