Hi,
How to get the lastmonth's end date? (have current date) through s shell script. I need to get it and pass it to a procedure.
Please advice.
Thanks in advance.
Hi,
How to get the lastmonth's end date? (have current date) through s shell script. I need to get it and pass it to a procedure.
Please advice.
Thanks in advance.
For future reference if someone reads this:
try cal
#!/bin/ksh
printf "%d %d" $(date "+%Y %m") | read year month
let month=$month-1
if [[ $month -eq 0 ]] ; then
let year=$year-1
let month=12
fi
cal $month $year | tr -s '\n' ' ' | awk '{print $NF}' | read day
printf "%d/%02d/%02d\n" $year $month $day
if [[ $month -eq 0 ]] ; then
let year=$year-1
let month=1
fi
Shouldn't this be ?
if [[ $month -eq 0 ]] ; then
let year=$year-1
let month=12
fi
January is month 1, so when you subtract 1 you get 0. And you rightly trap for it, decrementing the year but setting the month to 1 for January. I think you should set to 12 for December.
Perl-based approach to deriving backwards in time...I haven't quite bothered to try going back to the future as of yet. But it also handles Leap Years...
$ pl_end_of_last_month_0=`perl -e '\
> $y= time - (86400 * (localtime(time))[3]); \
> printf "%04d%02d%02d\n", (localtime($y))[5] + 1900 ,(localtime($y))[4] + 1 ,(localtime($y))[3] ; ' `
$ echo $pl_end_of_last_month_0
20070831
===
$ # Today...
$ pl_today_0=`perl -e '\
> $y= time - (86400 * $ARGV[0]); \
> printf "%04d%02d%02d\n", (localtime($y))[5] + 1900 ,(localtime($y))[4] + 1 ,(localtime($y))[3] ; ' 0 `
$ echo $pl_today_0
20070912
===
$ # Today minus 1... (um, yesterday...?)
$ pl_today_1=`perl -e '\
> $y= time - (86400 * $ARGV[0]); \
> printf "%04d%02d%02d\n", (localtime($y))[5] + 1900 ,(localtime($y))[4] + 1 ,(localtime($y))[3] ; ' 1 `
$ echo $pl_today_1
20070911
===
$ # Today minus a defined number...
$ my_number=3
$ pl_today_mynumber=`perl -e '\
> $y= time - (86400 * $ARGV[0]); \
> printf "%04d%02d%02d\n", (localtime($y))[5] + 1900 ,(localtime($y))[4] + 1 ,(localtime($y))[3] ; ' ${my_number} `
20070909
===
You are right. I was being bombed with other things when I did that... my bad.
And perl/python/C is better solution.
If you have ksh93 version h (released 1999) or later you can use the amazingly useful, but very poorly documented, %T operator to find specific dates easily
To print the date for the last day of last month do
$ printf "%(%Y-%m-%d)T\n" "final day last month"
2008-02-29
$
The %T format can also be invoked as %(subformat)T where subformat is any format that can be handled by the date(1) command.