2012-03-24 2 views

Antwort

3

Ich endete diese Lösung selbst und dachte, ich sollte die Lösung hier posten. Wenn jemand Verbesserungsvorschläge hat, können Sie diese gerne hinzufügen.

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

Es sieht aus wie der Eingang zu dem for-Schleife, 'ls -1R„$ base“. *', Brechen könnte, wenn jemand eine Datei im Verzeichnis wie 'base.apple' setzen, wo das Suffix nicht a Nummer. – Harvey

Verwandte Themen