Getting Proper Date Format in SH Script

There's a small SH script I'm trying to write where it will get the current month and find a log file that is based on the date.
Example: Today is February, so the log file is going to be 201102.log (2011 + 02)
An additional thing is that if today is the 1st of a month, it will also find the log file of the previous month.
In the example's case, the previous month's log file is 201101.log.

However, when I run my script, the previous month's log file that the script tries to look for is 20111.log, which obviously ends up failing.
What's the extra bit of code I need to make it look for 201101.log?
The script works fine if the previous month is Oct, Nov, or Dec as this has already been tested.

DATE_CMD=date

# SET DEBUG to 1 to printout debug data
DEBUG=0
# SET DEBUG_NO_ACTION to 1 to prevent file transfer and update actions
DEBUG_NO_ACTION=0


if [ ${DEBUG_NO_ACTION} == 1 ]; then
   echo WARNING: DEBUG_NO_ACTION set to 1, no file xfer or update will occur
fi

CURDAY=`eval ${DATE_CMD} '+%d'`
if [ ${DEBUG} == 1 ]; then
  echo CURDAY: $CURDAY
fi
if [ "$CURDAY" == "01" ]; then
    CURYEAR=`eval ${DATE_CMD} '+%Y'`
    CURMONTH=$((`eval ${DATE_CMD} '+%m'` - 1))
    
    if  [ "$CURMONTH" == "0" ]; then
        CURYEAR=$((`eval ${DATE_CMD} '+%Y'` - 1))
        CURMONTH=12
    fi
    
    FILENAME=$CURYEAR$CURMONTH.log
        if [ ${DEBUG} == 1 ]; then
          echo PREVIOUS MONTH FILENAME: $FILENAME
        fi
fi

Use printf to format the value:

CURMONTH=$(printf "%02d" $(($(eval date '+%m') - 1)))

And change the next line to:

    if  [ "$CURMONTH" == "00" ]; then

Awesomeness, this worked! Thanks so much! :slight_smile:

If you have GNU date you can also do:

FILENAME=$(date -d yesterday +%Y%m)

If not a not-so-portable method is to set TZ to 24 hours past your timezone. For example if you are in New York (GMT+5) use GMT+29:

FILENAME=$(TZ=GMT+29 date +%Y%m)