Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script log file rotation

My bash script produces a log file. Now i'd like to implement some log file rotation.
Let's say the first time it's called somelog.log, the next time it's renamed to somelog.log.1 and the new log file somelog.log.
The third time the new log is somelog.log again, but somelog.log.1 is renamed to somelog.log.2 and the old somelog.log to somelog.log.1.
I would be able to grant a maximum of eg 5.

Is this done before (sample script), any suggestions. I appreciate any advice.

like image 339
John Doe Avatar asked Sep 11 '10 06:09

John Doe


People also ask

How do you rotate a log file in Linux?

A number of log files are set up for rotation as soon as a Linux system is installed. In addition, certain applications add their own log files and rotation specs when they are installed on the system. The configuration files for log-file rotations can be found in the /etc/logrotate.

How do you force a log to rotate?

If you want to force Logrotate to rotate the log file when it otherwise would not have, use the --force flag: logrotate /home/sammy/logrotate. conf --state /home/sammy/logrotate-state --verbose --force.

What is rotate log file?

In information technology, log rotation is an automated process used in system administration in which log files are compressed, moved (archived), renamed or deleted once they are too old or too big (there can be other metrics that can apply here).


1 Answers

Try this bash function, it takes two parameters:

  1. number of maximum megabyte the file should exceed to be rotated (otherwise is let untouched)
  2. full path of the filename.

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 $?
}
like image 178
bzimage Avatar answered Sep 18 '22 23:09

bzimage