Harvey
Harvey

Reputation: 5821

Rotate a set of logfiles named file, file.0, file.1, etc. in shell script

I have a directory full of log files that I need to rotate using a posix shell script on an embedded system. They are named file, file.0, file.1 and so on. I didn't see this question already asked and had trouble finding it on google.

Upvotes: 1

Views: 1694

Answers (1)

Harvey
Harvey

Reputation: 5821

I ended up solving this myself, and thought I should post the solution here. If anyone has suggestions for improvement, feel free to add them.

# Usage:  rotate_logs base [max]
# Example:
#         rotate_logs messages 10    # Rotate "messages" files keeping only 10 rotated files.

rotate_logs() {
  #set -x
  local base="$1"
  # ensure we have a base and it is not null
  if [ $# -lt 1 -o -z "$1" ]; then
    echo "Usage:  $0 base [max]" >&2
    echo "Example:" >&2
    echo -e "\t$0 messages 10\t# Rotate \"messages\" files keeping only 10 rotated files." >&2
    return 1
  fi
  # see if we were given a max number and make sure it is a number
  if [ $# -ge 2 ]; then
    if ! echo "$2" | egrep -q '^[0-9]+$'; then
      echo "Maximum number, \"$2\", must be a number." >&2
      return 1
    fi
    local max=$2
  fi
  local i
  local n
  # Get a list of all of the already rotated files in reverse
  # base.3 base.2 base.1
  for i in $(ls -1r "$base".*); do
    # Calculate the next number for the current file, i.e. 4 for base.3
    n=$((1 + $(echo $i | sed 's,'"$base"'.,,')))
    # If the new file number is greater than max, delete it.
    if [ $n -gt ${max:-999999} ]; then
      rm -rf "$i"
    else
      # otherwise move the file to the new number
      mv $i "$base".$n
    fi
  done
  # If there is a "base" file with no extension move that now.
  if [ -e "$base" ]; then
    mv "$base" "$base".0
  fi
}

Upvotes: 3

Related Questions