Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ensure variable has 2 chars 1

Status
Not open for further replies.

kasparov

Programmer
Feb 13, 2002
203
GB
I can think of a few ways to do this - but they are all long winded & can no doubt be improved on.

I need to set an environment variable to the number of the month before last. What I mean is that when I run my script in March I want $MONTH=01, in January $MONTH=11.

- date +%m gives me '03' for month,
- I can use expr to subtract 2, but this gives me '1' not '01' (& won't work in Jan or Feb anyway so I'd have to do something fancy for these months)
- I could use sed to prefix a '0' where required

As usual I'd be interested to hear what the experts suggest!

The usual thanks in advance ... Chris
 
typeset -Z2 MONTH

MONTH=2
echo $MONTH
02


HTH,

p5wizard
 
nothing fancy really:

typeset -Z2 MONTH
typeset -Z4 YEAR

MONTH=$(date +'%m')
YEAR=$(date +'%Y')

(( MONTH=MONTH-2 ))
if (( MONTH<1 ))
then
(( YEAR=YEAR-1 ))
(( MONTH=MONTH+12 ))
fi

echo $YEAR-$MONTH


HTH,

p5wizard
 
Thanks p5wizard - that's neat enough for me!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top