1
我有一個滿足日誌文件的目錄,我需要在嵌入式系統上使用posix shell腳本進行輪換。它們被命名爲file,file.0,file.1等等。我沒有看到這個問題已經問過,並且很難在谷歌上找到它。在shell腳本中旋轉一組名爲file,file.0,file.1等的日誌文件
我有一個滿足日誌文件的目錄,我需要在嵌入式系統上使用posix shell腳本進行輪換。它們被命名爲file,file.0,file.1等等。我沒有看到這個問題已經問過,並且很難在谷歌上找到它。在shell腳本中旋轉一組名爲file,file.0,file.1等的日誌文件
我最終自己解決了這個問題,並認爲我應該在這裏發佈解決方案。如果有人有改進建議,請隨時添加。
# 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
}
它看起來像for循環的輸入'ls -1r「$ base」。*',如果有人將文件放入類似'base.apple'的目錄中,後綴不是數。 – Harvey 2013-03-12 00:22:14