在shell脚本中旋转一组名为file,file.0,file.1等的日志文件

时间:2012-03-24 07:29:48

标签: shell logging

我有一个充满日志文件的目录,我需要在嵌入式系统上使用posix shell脚本进行旋转。它们被命名为file,file.0,file.1等。我没有看到这个问题已经被问及在谷歌上找不到它。

1 个答案:

答案 0 :(得分:3)

我最终解决了这个问题,并认为我应该在这里发布解决方案。如果有人有改进建议,请随时添加。

# 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
}