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.

Friday, November 29, 2013

Another Simple Bash Function for Log Rotation Based on Size

As a follow up to my previous post, "Simple Bash Log Rotate Function", here's another function to rotate your logs. The difference is that this function allows you to specify as parameters how many files to keep and how big the files should be (in Mb).

LogRotate () {
# USAGE - LogRotate [files to keep] [size]
export LOG=scpp-wm.log
if [[ $# -ne 2 ]] ; then
  KEEP=5
  SIZE=5242880
else
  KEEP=$1
  SIZE=$(echo "$2 * k" | bc)
fi

if [[ $KEEP -gt 10 ]] ; then
  echo "Max amount of files to keep is 10"
  return 1
fi

for T_LOG in ${LOG}.* ; do 
  cat $T_LOG >> tmp1-${LOG} 
done

split -a 1 -b $SIZE -d tmp1-${LOG} ${LOG}. 2> /dev/null

P_CNT=0
CNT=1
while [[ $CNT -le $KEEP ]] ; do
  mv ${LOG}.${P_CNT} tmp.${LOG}.$CNT
  let CNT=CNT+1
  let P_CNT=P_CNT+1
done

rm ${LOG}*
rm tmp1-${LOG}
rename 'tmp.' '' tmp.${LOG}.?
}

LogRotate $1 $2

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
}