How to pass current year and month in FOR LOOP in UNIX shell scripting?

Hi Team,

I have created a script and using FOR LOOP like this and it is working fine.

for Month in  201212 201301 201302 201303  
do

echo "Starting the statistics gathering of $Month partitions "  

done

But in my scripts the " Month " variable is hard-coded. Can you please any one help me how to capture the month variable in UNIX in this format ("YYYYMM") and pass it dynamically in the FOR LOOP.

Thanks in Advance
Shoan

If your date command supports -d option, then try:-

#!/bin/bash

DT="20121201"

for count in {1..5}
do
        echo $DT | cut -c 1-6
        DT=$( date -d"$DT +1 month" +"%Y%m%d" )
done

Capture from where?

You could init month and year vars and increment in a loop like this:

YEAR=`date +%Y`
MONTH=`date +%m`
for i in 1 2 3 4
do
   printf "Starting the statistics gathering of %d%02d partitions \n" $YEAR $MONTH
   let MONTH=10#$MONTH+1
   if [ $MONTH -gt 12 ]
   then
      let YEAR=YEAR+1
      let MONTH=1
   fi
done

Note the 10# above is required for bash, as leading zeros in Aug and Sep cause bash some issues as it tries to convert to octal.