Monday, November 10, 2014

Rotating Log Files

This script moves on log files listed on the command line. It keeps all but the most recent one
compressed, and removes the last one once there are more than CYCLES of them. For example,
CYCLES=3 ; rotate messages Would have the following effects.

messages --> messages.1
messages.1 --> messages.2.gz
messages.2.gz --> messages.3.gz
messages.3.gz --> removed


script :


#!/bin/sh
# Rotate a log file and keep N copies
# Mostly stolen from inn
CYCLES=${CYCLES-5}
COMPRESS=/usr/local/bin/gzip
Z=.gz
for F in $* ; do
## Compress yesterday’s .1
test -f ${F}.1 \
&& ${COMPRESS} <${F}.1 >${F}.1${Z} \
&& rm -f ${F}.1 \
&& chmod 0440 ${F}.1${Z}
## Do rotation.
EXT=${CYCLES}
rm -f ${F}.${CYCLES}${Z}
while [ ${EXT} -gt 0 ] ; do
NEXT=${EXT}
EXT=‘expr ${EXT} - 1‘
test -f ${F].${EXT}${Z} \
&& rm -f ${F}.${NEXT}${Z} \
&& mv ${F}.${EXT}${Z} ${F}.${NEXT}${Z}
done
mv ${F} ${F}.1
done

No comments:

Post a Comment