Wednesday, November 24, 2010

Adding one month (30-31 days) in UNIX SOLARIS


#! /usr/bin/ksh
d=`date +%d`
m=`date +%m`
y=`date +%Y`
if [ $m%2 -eq 0 ]
then
d1=`expr $d + 30`
d=expr $d1 - 30`
else
d1=`expr $d + 31`
d=expr $d1 - 31`
fi
if [ $m -eq 12 ]
then
y=`expr $y + 1`
m=0
fi
m=`expr $m + 1`
if [ $m -lt 10 ]
then
m=0$m
fi
echo "$y-$m-$d"
exit 0

3 comments:

cfajohnson said...

> #! /usr/bin/ksh
> d=`date +%d`
> m=`date +%m`
> y=`date +%Y`


Three calls to date are not only unnecessary, but can break your script if a date boundary is crossed between calls. You should use a singl call to date so that all variables are populated with the same date:


eval "$(date "+d=%d m=%m y=%Y")"


> d1=`expr $d + 30`

You are using ksh; why are you doing integer arithmetic with an external command? Use the shell:

d1=$(( $d + 30 )) ## valid in any POSIX shell (bash, ash, dash, ksh).

Manu Swami said...

"Three calls can break your script if a date boundary is crossed between calls."

You are correct..

Thanks for pointing this out :)

Unknown said...

It was very nice article and it is very useful to Linux learners.We also provide Linux online training

 

Blogger news

Blogroll