一个演算日期的shell程序
#!/bin/bash
usage()
{
echo " useage:"
echo " date_offset.sh YYYYMMDD offset"
echo " such as:"
echo " date_offset.sh 20011001 -1 : 20010930"
echo " date_offset.sh 20011001 5 : 20011006"
exit 2
}
#get the days of some month
get_mon_days()
{
Y=`expr substr $1 1 4` #get the year string
M=`expr substr $1 5 2` #get the month string
r1=`expr $Y % 4`
r2=`expr $Y % 100`
r3=`expr $Y % 400`
case $M in
01|03|05|07|08|10|12) days=31;;
04|06|09|11) days=30;;
esac
#check if the leap year
if [ $M -eq 02 ]
then
if [ r1 -eq 0 -a r2 -ne 0 -o r3 -eq 0 ]
then
days=29
else
days=28
fi
fi
echo $days
}
#get the date of yesterday
yesterday()
{
Y=`expr substr $1 1 4`
M=`expr substr $1 5 2`
D=`expr substr $1 7 2`
YY=`expr $Y - 1`
MM=`expr $M - 1`
DD=`expr $D - 1`
MM=`printf "%02d" $MM`
DD=`printf "%02d" $DD`
dd=$Y$MM
dad=`get_mon_days $dd`
be_date=$Y$M$DD
if [ $D -eq 01 ]
then
if [ $M -ne 01 ]
then
be_date=$Y$MM$dad
fi
if [ $M -eq 01 ]
then
be_date=$YY"1231"
fi
fi
echo $be_date
}
#get the date of tomorrow
tomorrow()
{
Y=`expr substr $1 1 4`
M=`expr substr $1 5 2`
D=`expr substr $1 7 2`
YY=`expr $Y + 1`
MM=`expr $M + 1`
DD=`expr $D + 1`
MM=`printf "%02d" $MM`
DD=`printf "%02d" $DD`
r1=`expr $Y \% 4`
r2=`expr $Y \% 100`
r3=`expr $Y \% 400`
next_date=$Y$M$DD
if [ $D -eq 30 ]
then
case $M in
04|06|09|11) next_date=$Y$MM"01";;
esac
fi
if [ $D -eq 31 ]
then
next_date=$Y$MM"01"
case $M in
12) next_date=$YY"0101";;
esac
fi
if [ $M -eq 02 ]
then
if [ r1 -eq 0 -a r2 -ne 0 -o r3 -eq 0 ]
then
if [ $D -eq 29 ]
then
next_date=$Y$MM"01"
fi
else
if [ $D -eq 28 ]
then
next_date=$Y$MM"01"
fi
fi
fi
echo $next_date
}
#main function
# check the num of args
if [ $# -ne 2 ]
then
echo "error num of args!"
usage
fi
# check the first arg
if [ `expr length $1` -ne 8 ]
then
echo "error the first arg!"
usage
fi
TMP_YEAR=`expr substr $1 1 4`
TMP_MONTH=`expr substr $1 5 2`
TMP_DAY=`expr substr $1 7 2`
#echo $TMP_YEAR
#echo $TMP_MONTH
#echo $TMP_DAY
if [ `expr length $TMP_YEAR` -ne 4 ]
then
echo "error date format!"
usage
fi
if [ $TMP_MONTH -lt 1 ] || [ $TMP_MONTH -gt 12 ]
then
echo "error date format!"
usage
fi
LAST_DAY=`echo \`cal $TMP_MONTH $TMP_YEAR\`|tail -n1|awk '{print $NF}'`
if [ $TMP_DAY -lt 1 ] || [ $TMP_DAY -gt $LAST_DAY ]
then
echo "error date format!"
usage
fi
#check the second arg
expr $2 + 0 >/dev/null 2>&1
if [ ! $? ]
then
echo "arg error!"
usage
fi
TMP_DATE=$1
if [ $2 -lt 0 ]
then
INC=-1
COUNT=$2
else
INC=1
COUNT=`expr 0 - $2`
fi
#compute the date of yesterday or tomorrow each time
while [ $COUNT -lt 0 ]
do
if [ $INC -gt 0 ]
then
TMP_DATE=`tomorrow $TMP_DATE`
else
TMP_DATE=`yesterday $TMP_DATE`
fi
COUNT=`expr $COUNT + 1`
done
echo $TMP_DATE