Given a start date, I set the date to the end of the month of the previous year, and then try to loop 12m using a bash while loop.
The following loop never exits, and the date eventually skips from the end of the month to the beginning of the next one.
startdate="2014-06-22"
cod=${startdate:0:7}-01
echo $cod
cod=$( date --date "$cod -1 year +1 month -1 day " +"%Y-%m-%d" )
echo "$cod , $startdate "
while [ "$cod" < "$startdate" ];
do
echo $cod
cod=$( date --date "$cod +1 month" +"%Y-%m-%d" )
echo $cod
done
What I'm expecting is
2013-06-30
2013-07-31
2013-08-31
2013-09-30
2013-10-31
2013-11-30
2013-12-31
2014-01-31
2014-02-28
2014-03-31
2014-04-30
2014-05-31
So what you want is the last day of each month, but you are trying to get it by taking the first "last day of the month" and adding one month each time. That doesn't work because you get January 30th and then March 2nd rather than February 28th, because February is weird and "+1 month" is weird :-)
$ date -d '2014-01-30'
Thu Jan 30 00:00:00 GMT 2014
$ date -d '2014-01-30 +1 month'
Sun Mar 2 00:00:00 GMT 2014
To get the last day of each month you need to repeat the trick you use on the first date - find the first day of the following month and then -1 day from it.
#!/bin/bash
startdate="2014-06-22"
cod=${startdate:0:7}-01
cod=$( date --date "$cod -1 year +1 month -1 day " +"%Y-%m-%d" )
for i in $(seq 1 12); do
echo $cod
cod=$( date --date "$(date --date "$cod +32 day" +"%Y-%m-01") -1 day" +"%Y-%m-%d" )
done
Which outputs:
$ ./twelve_months.sh
2013-06-30
2013-07-31
2013-08-31
2013-09-30
2013-10-31
2013-11-30
2013-12-31
2014-01-31
2014-02-28
2014-03-31
2014-04-30
2014-05-31
Note that I also changed the loop to a straight 1 .. 12
instead of a while loop with a logic check. The while loop seemed needlessly complicated when you know you always want twelve dates.