Thursday, December 20, 2007

Rotating log files
If in case you need to write a script to rotate log files that you have.

#!/bin/sh

# Usage: rotate

PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin ; export PATH

logfile=$1 # name of the logfile without any extensions
to_num=$2 # extension that the rotated file will have

while [ $to_num -gt 1 ] ; do
from_num=`expr $to_num - 1` # extension of the file to be rotated
if [ -f $logfile.$from_num ] ; then # if the logfile already exists
mv $logfile.$from_num $logfile.$to_num
elif [ -f $logfile.$from_num.gz ] ; then # in case they are compressed
mv $logfile.$from_num.gz $logfile.$to_num.gz
fi
to_num=$from_num
done

if [ -f $logfile ] ; then # sanity check
cp $logfile $logfile.1
cp /dev/null $logfile # truncates the file
gzip --quiet $logfile.1 # compress it to save space
fi

Got it from http://www.aoc.nrao.edu/~krowe/TCC/sysadmin/topics/tools.html

No comments: