Sunday, July 1, 2012

How to get the yesterday's date in Borne shell?

I tried to write a script that had the capability to retrieve 
yesterday's data. To do this, I used today's date with the condition of "expr 
$TodayDate -1" to get the day format of yesterday. It worked fine for the 
first month, but I encountered an error when the current date turned to 
the first day of the second month. For example, if today is 20040601, 
with the expression of"expr $TodayDate -1", it would be 20040600 instead 
of 20040531. Can anyone help?


There are a few ways by which you can get yesterdays date (perl is one solution), but the most easy and simple solution is to get GNU date from gnu.org ... 

GNU_date_PATH/date -d yesterday 

will give you yesterdays date ... 

GNU date is part of the sh-utils package, you can get it from here: 
ftp://ftp.ftp://ftp.gnu.org/gnu/sh-utils/sh-utils-2.0.tar.gz/gnu/sh-utils/sh-utils-2.0.tar.gz 
If you are not willing to download the sh-utils package from gnu.org then here is the perl method of getting yesterdays date ... 

perl -le 'print scalar localtime time - 86400' 
I found this logic in one of my scripts on the production server. You could 
try using this... 

#! /usr/bin/ksh 

# Today's date formatted: 
TODAY=`date +'%m-%d-%Y'` 

# Get individual elements 
MONTH=`echo $TODAY | cut -d'-' -f1` 
DAY=`echo $TODAY | cut -d'-' -f2` 
YEAR=`echo $TODAY | cut -d'-' -f3` 

if [[ `expr $DAY + 0` -eq 1 ]]; then 
if [[ $MONTH -eq 1 ]]; then 
MONTH=12 
YEAR=`expr $YEAR - 1` 
else 
MONTH=`expr $MONTH - 1` 
fi 

cal $MONTH $YEAR | grep 31 1>/dev/null 2>&1 
if [[ $? -eq 0 ]]; then 

DAY=31 
else 
DAY=30 
fi 
else 
DAY=`expr $DAY + 0` 
DAY=`expr $DAY - 1` 
fi 

if [[ `echo $MONTH | wc -c` -eq 2 ]]; then 
MONTH=0$MONTH 
fi 
if [[ `echo $DAY | wc -c` -eq 2 ]]; then 
DAY=0$DAY 
fi 

# Previous day in the same format, without hyphens 
NEW_DATE=$MONTH$DAY$YEAR 
Change the line TODAY=$1 to TODAY=`date +'%m-%d-%Y'`. I had changed the line 
to test the logic again, and forgot to put it back. 

0 comments:

Post a Comment

 
Design by BABU | Dedicated to grandfather | welcome to BABU-UNIX-FORUM