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

No comments: