Wednesday, 18 May 2011

Unix Shell Script to write logs on daily basis

#!/bin/ksh
#/usr/local/bin/yesterday
set -A DAYS Sat Sun Mon Tue Wed Thu Fri Sat
set -A MONTHS Dec Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
YESTERDAY=$((`date +%d` -1))
MONTH=`date +%m`
YEAR=`date +%Y`
NDAY=`date +%u`
WEEKDAY=${DAYS[`date +%u`]}
if [ $YESTERDAY -eq "0" ]
then
        MONTH=$((MONTH-1))
        if [ $MONTH -eq "0" ]
        then
                MONTH=12
                YEAR=$((YEAR-1))
        fi
set `cal $MONTH $YEAR`
shift $(($# - 1))
YESTERDAY=$1
fi
TMONTH=${MONTHS[MONTH]}
# uncomment next line for debugging
echo $WEEKDAY $YESTERDAY $MONTH $TMONTH $YEAR
mkdir -p /oldlogs/$YEAR/$TMONTH 2>/dev/null
cp log.old /oldlogs/$YEAR/$TMONTH/$WEEKDAY$YESTERDAY

Above script will take a logs backup on daily basis.for example today is Thursday May 18. We want to copy the log to the directory /oldlogs/2011/May/Tue17 (it's yesterday's log we are copying).
and it works correctly for any day, automatically taking leap years into account -assuming your version of "cal" handles leap years correctly!

No comments:

Post a Comment