Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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`
fi

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
1  
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
add comment

2 Answers 2

$ month=5; year=2012 
$ perl -e 'printf"%02d/%04d\n",@ARGV' $month $year
05/2012

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
05/2012

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

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

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

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

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

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

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
add comment

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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