Use date command to find last month

#!/usr/bin/ksh

Does anyone have a good way to set a variable to last month?

For example, today is 20070810. I would like to use the date command to set a variable to last months %m code, which is 07. If I pluck this months value (08) and user expr to do simple math on it, it returns 7 (not 07). If I use that to write my script, adding a zero in front of it, the script will break when a double digit month comes along.

I either need to get last months two digit %m code from the date command, or I need a way to force the expr command to use two digits.

Any ideas?

This will not work for a variety of reasons.
What happens on March 31 - You'll go back to February 31?
What happens on Jan 10?

Check the FAQ for perderabo's datecalc script. It will do just what you want.

echo $(date -d"1 month ago" "+%G%m%d" | cut -c5-6)

or

echo $(date -d"1 month ago" "+%m" )

lorcan -
Your solution is just fine - but not all versions of date support -d

Yes thats true Jim. I should have posted that as a note. :slight_smile:

Yeah. That's some script. I feel like a total noob after reading that.

I appreciate the input. I think I am going to approach this from another angle, though.