Adding Previous Month To Filename

Dear experts,

I'm using solaris 5.10 and bash. I want to zip file "Amount.txt" to "Amount.zip" and rename it to "Amount_<prev_month>_<this year>.zip". For example, file for this month should be renamed to "Amount_06_2012.zip", for next month it should be "Amount_07_2012.zip". I have no problem for zipping the file. Here's the script but it's not working:

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

mv Amount.zip Amount_`$lmonth`_`$year`.zip

When I executed it, it shows:

./script.sh: 6: not found
./script.sh: 2012: not found

Then the zip file renamed to "Amount__.zip"

Best regards,
Kris Adrianto

For previous month use this...

date --date="last month" +%m_%Y
06_2012

Use below command instead of your mv.

mv Amount.zip Amount_$lmonth_$year.zip

almost there.. but when I use this, it only shows: "Amount_2012.zip" not "Amount_6_2012.zip". Then I erased the $year, then it shows "Amount_6.zip".

L_Date=`date --date="last month" +%m_%Y`
mv Amount.zip Amount_$L_Date.zip
1 Like

Hi pamu.. i think your code isn't applicable in solaris with bash..
When I execute the first line of your code, it shows:

date: illegal option -- date=last month
usage:  date [-u] mmddHHMM[[cc]yy][.SS]
        date [-u] [+format]
        date -a [-]sss[.fff]
month=`date +%m`
year=`date +%Y`
lmonth=`expr $month - 1`
if test "$lmonth" = "0"
then
lmonth=12
year=`expr $year - 1`
fi

L_date=$lmonth"_"$year

mv Amount.zip Amount_$L_Date.zip

Now it will work ...

but from your script we are getting previous month as 6 not 06..

1 Like

It works now.. Thanks so much!

---------- Post updated 07-17-12 at 11:03 AM ---------- Previous update was 07-16-12 at 05:03 PM ----------

By the way, if i want to display month as "Jun" not "6", i have to use:

month=`date +%h`

instead of

month=`date +%m`

But if i use the new parameter, I cannot directly substract the month to get the previous month. Is there way to solve this so I can use "Jun" not "6"?

Regards,
Kris Adrianto

1)

date --date="last month" +%h
Jun

2)

date -d'last-month' +%h_%Y
Jun_2012

3) Modification to your code just add below lines to it...

L_date=$lmonth"/15/"$year

date --date="$L_date" +"%h_%Y"