Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have this script:

day=`date +%d`
month=`date +%m`
year=`date +%Y`
lmonth=`expr $month - 1`
if test "$lmonth" = "0"
then lmonth=12
year=`expr $year - 1`

The result when I call $lmonth/$year is 9/2012 How can I make it output 09/2012?

When the month is 10, 11 or 12 I don't want it to be 010, 011, or 012 respectively.

I want to put the $year and $lmonth when I call a table or file with period. For example, table_extra201209.

How do I add the extra zero for months from 1 (January) to 9 (September)?

I try all the answer here, but umm.. I forgot to mention something.. I want to put the $year and $lmonth when I call a table or file with periode, for example table_extra201209 how to put it on that with "0" attach before "9"..? thanks again :)

share|improve this question
Needs less CAPS, thank you very much – Ivo Flipse Oct 30 '12 at 9:24
Needs more sensible things when edits clash, too :-( – Joey Oct 30 '12 at 9:24
$ month=5; year=2012 
$ perl -e 'printf"%02d/%04d\n",@ARGV' $month $year

I don't recall if Bash has a printf or sprintf function, it probably has something equivalently useful.

Yes, bash does

$ month=5
$ year=2012
$ printf "%02d/%04d\n" $month $year

or, if you need the result in a variable use -v

$ printf -v expiry "%02d/%04d" $month $year
$ echo  $expiry

Also, you don't need to invoke date so many times

$ d=$(date '+%Y %m %d %H %M %S')
$ a=( $d )
$ echo ${a[0]}
$ echo ${a[1]}
$ echo ${a[2]}
$ echo ${a[3]}
$ echo ${a[4]}
$ echo ${a[5]}

Finally, date by itself can often give you what you want

$ minsec=$(date "+%M/%S")
$ echo $minsec

You probably know this, but if you decrement the month, you have allow for 1 - 1 = 12 and decrement the year and check the day number is in range (not 31st Feb, not 29th Feb unless leap year, allowing for calendar changes at various dates in various locales). It is often better to use a scripting language that has good date-handling modules.

share|improve this answer

You could test whether the number is less than 10 and only if that is the case add a 0 in front of it. So, try to append the following to your script:

[ $lmonth -lt 10 ] && lmonth=0$lmonth
share|improve this answer

protected by Community Dec 8 '15 at 12:05

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.