Blog is moving

My blog is moving to http://victormendonca.com/blog/. If you are looking for a specific or older post you are in the right place Otherwise check out my new page for more up to date content.

Tuesday, November 26, 2013

Simple Bash Log Rotate Function

Here's a simple function that you can add to your Bash script to rotate a log. This function will rotate the log everytime the script runs, up to 5 logs.

You can modify it to meet your needs.

# Log rotation
LOG_DIR=${HOME}/bin/log
LOG="${LOG_DIR}/my_script.log"

LogRotate () {
# Deletes old log file
if [ -f $LOG ] ; then
  CNT=5
  let P_CNT=CNT-1
  if [ -f ${LOG}.5 ] ; then
    rm ${LOG}.5
  fi
  
  # Renames logs .1 trough .4
  while [[ $CNT -ne 1 ]] ; do
    if [ -f ${LOG}.${P_CNT} ] ; then
      mv ${LOG}.${P_CNT} ${LOG}.${CNT}
      let CNT=CNT-1
      let P_CNT=P_CNT-1
    fi
  done

  # Renames current log to .1
  mv $LOG ${LOG}.1
  echo "" > $LOG
fi
}

5 comments:

32bitfloat said...

Many thanks, works like a charm...

...except that you do not have yet so many logfiles (4 in this case), then you end up in an endless loop ;)


One may want to change the loop-part to

while [[ $CNT -ne 1 ]] ; do
if [ -f ${LOG}.${P_CNT} ] ; then

mv ${LOG}.${P_CNT} ${LOG}.${CNT}
fi

let CNT=CNT-1
let P_CNT=P_CNT-1
done

32bitfloat said...

Many thanks, works like a charm...

...except that you do not have yet so many logfiles (4 in this case), then you end up in an endless loop ;)


One may want to change the loop-part to

while [[ $CNT -ne 1 ]] ; do
if [ -f ${LOG}.${P_CNT} ] ; then

mv ${LOG}.${P_CNT} ${LOG}.${CNT}
fi

let CNT=CNT-1
let P_CNT=P_CNT-1
done

to prevent this.

Saj/Saju said...

Thanks for the quick solution.
I just modified it little more - to make the function take parameters so that you can specify the number of files to retain etc.

#!/bin/bash

# Log rotation
LOG_DIR=.
LOG="${LOG_DIR}/my_script.log"

LogRotate () {
local f="$1"
local limit=$2
# Deletes old log file
if [ -f $f ] ; then
CNT=${limit}
let P_CNT=CNT-1
if [ -f ${f}.${limit} ] ; then
rm ${f}.${limit}
fi

# Renames logs .1 trough .4
while [[ $CNT -ne 1 ]] ; do
if [ -f ${f}.${P_CNT} ] ; then
mv ${f}.${P_CNT} ${f}.${CNT}
fi
let CNT=CNT-1
let P_CNT=P_CNT-1
done

# Renames current log to .1
mv $f ${f}.1
echo "" > $f
fi
}

LogRotate $LOG 10

Yuri Weinstein said...

If I want to keep 100 files just to replace 5 with 100 ?

Stephen Raj Jayaraj said...

I have been looking for this quite a long time. Thanks a lot. Works perfect!