cancel
Showing results for 
Search instead for 
Did you mean: 

log rotate script for linux

SOLVED
Go to solution
Adithyan
Frequent Advisor

log rotate script for linux

Hello all,

Need some help in writing a custom script to rotate my /var/log/messages files in my Linux server.

Instead of the syslog rotating my /var/log/messages weekly, I would like to rotate the file in a daily basis and save file like day1, day2... in my /var/log directory.

My /var/log directory would look like /var/log/day1 /var/log/day2 instead of /var/log/messages /var/log/messages.1

Please let me know how to establish this?

Thanks in advance
Adithyan
Keen to learn HP UX
2 REPLIES
Alexander Chuzhoy
Honored Contributor
Solution

Re: log rotate script for linux

First, set the respective line in /etc/syslog.conf to point to /var/log/day1 instead of to /var/log/messages;
then copy the following to the file,make it executable and schedule it to run on a daily basis (assuming you want to have only 5 copies):
#!/bin/bash
maxdays=5;rm -f day${maxdays} ; for i in `seq 1 ${maxdays}`; do num=`expr ${i} - ${maxdays}`;num=`expr ${num} \* -1`;echo "$num";newnum=`expr ${num} + 1`; if [ -f day${num} ]; then mv day${num} day${newnum};fi; done ; touch day1

And most important - don't forget to assign points.
alang
Occasional Advisor

Re: log rotate script for linux

Here is my script that is used for rotating the listener log of Oracle.

Put it into crontab so that be executed at the fixed period.

===============================================
#!/usr/bin/bash

# lsnrlog-rotate.sh - Automatical rotate the listener.log
# History:
# 2008/2/12(alang)
#
. $HOME/.profile

LOGDIR="$ORACLE_HOME/network/log/"
LOGNAME="listener.log"
LSNR_CTL="$ORACLE_HOME/bin/lsnrctl"
DURATION=3

BK_LOG1="${LOGNAME}.1"
BK_LOG2="${LOGNAME}.2"
BK_LOG3="${LOGNAME}.3"
BK_LOG4="${LOGNAME}.4"

echo "**** $(date +'%y/%m/%d@%H:%M') ****"

if [ ! -w $LOGDIR -o ! -x $LOGDIR ]; then
echo "$0: you don't have the appropriate permission in $LOGDIR" >&2
exit 1
fi

cd $LOGDIR
if [ -f "$BK_LOG1" ];then
if [ -z $(find "$BK_LOG1" -mtime +$DURATION -print 2> /dev/null) ]
then
echo "$LOGNAME's most recent backup is more recent then $DURATION days: exiting"
exit 0
fi
fi
echo "Rotating log $LOGNAME (using a $DURATION day schedule)"

if [ -f "$BK_LOG3" ]; then
echo "... $BK_LOG3 -> $BK_LOG4"; mv -f "$BK_LOG3" "$BK_LOG4"
fi

if [ -f "$BK_LOG2" ]; then
echo "... $BK_LOG2 -> $BK_LOG3"; mv -f "$BK_LOG2" "$BK_LOG3"
fi

if [ -f "$BK_LOG1" ]; then
echo "... $BK_LOG1 -> $BK_LOG2"; mv -f "$BK_LOG1" "$BK_LOG2"
fi

if [ -f "$LOGNAME" ]; then
$LSNR_CTL set log_status off
cp -f "$LOGNAME" "$BK_LOG1"
cat /dev/null > "$LOGNAME"
$LSNR_CTL set log_status on
echo "... $LOGNAME -> $BK_LOG1"
fi

#EOF