Bash script log file rotation

My bash script creates a log file. Now I would like to implement some rotation of the log file.
Say the first time he called somelog.log , the next time you rename it somelog.log.1 and the new log file somelog.log .
The third time, the new log somelog.log is again, but somelog.log.1 is renamed to somelog.log.2 and the old somelog.log to somelog.log.1 .
I would like able to provide a maximum, for example, 5.

This is done earlier (sample script), any suggestions. I appreciate any advice.

+7
file bash logging rotation
source share
2 answers

Try this bash function, it takes two parameters:

  • The maximum megabyte must exceed the file that must be rotated (otherwise it will not be touched)
  • full path to the file name.

A source:

function rotate () { # minimum file size to rotate in MBi: local MB="$1" # filename to rotate (full path) local F="$2" local msize="$((1024*1024*${MB}))" test -e "$F" || return 2 local D="$(dirname "$F")" local E=${F##*.} local B="$(basename "$F" ."$E")" local s= echo "rotate msize=$msize file=$F -> $D | $B | $E" if [ "$(stat --printf %s "$F")" -ge $msize ] ; then for i in 8 9 7 6 5 4 3 2 1 0; do s="$D/$B-$i.$E" test -e "$s" && mv $s "$D/$B-$((i+1)).$E" # emtpy command is need to avoid exit iteration if test fails: :; done && mv $F $D/$B-0.$E else echo "rotate skip: $F < $msize, skip" fi return $? } 
+2
source share

I just made a bash script for this: https://github.com/lingtalfi/logrotator

It basically checks the size of your log file, and if it exceeds an arbitrary threshold, it copies the log file to the log directory.

It is cron friendly, or you can use it manually too.

A typical command looks like this:

 > ./logrotator.sh -f private/log -m {fileName}.{datetime}.txt -v 
0
source share

All Articles