Bash脚本日志轮换

时间:2018-12-07 03:43:43

标签: bash rotation

您能帮我解决日志轮换问题吗?

我的bash脚本需要一个必需的整数参数和一个可选的字符串参数。整数是要保留的先前日志的数量,而字符串是日志要保留在的目录的路径(默认为log)。在此程序中,我应验证是否提供了整数参数,该参数是一个数字。如果提供了第二个参数,请确保给定的路径是目录,并且我对此目录具有写权限。不必担心单个日志文件具有写权限。

以下是该程序的几个示例运行。以“>”开头的行是程序的响应。

不打印以“#”开头的行,而是描述程序将执行的操作。

./logrot
    
> number of days of logs to keep is required to be a non-negative integer
    
./logrot -3
    
> number of days of logs to keep is required to be a non-negative integer
./logrot 5 Not_A_Writeable_Directory
    
>  Not_A_Writeable_Directory must be a path to a log directory with write access for $USER
./logrot 1
    
#moves log/*.0.log to log/*.1.log
    
#creates new log/*.0.log
    
#deletes all other .log files
./logrot 2 otherfolder
#moves otherfolder/*.1.log to otherfolder/*.2.log
#moves otherfolder/*.0.log to otherfolder/*.1.log
#creates new otherfolder/*.0.log
#deletes all other .log files

我的bash脚本代码:

#!/bin/bash

if [-z "$1"] || ["1" -lt "0"]; then
    echo "number of days of logs to keep is required to be a non-negative integer"
    exit
    else
    count="$1"
fi

if [-z "$2"]; then
    dir=~/log
    else
    dir=$2
fi

if [ ! -d "$dir"]: then
    #echo "$dir must be a path to a log directory with write access for $USER
    #exit
    mkdir ~/log
    chmod 777 ~/log
    touch ~/log/*.0.log
fi

for (( i=$count-1; i>=0; i--))
    do
    next=$(($i+1))
    if [ ! -f "$dir/*.$i.log"]; then
    echo "Directory $dir/*.$i.log does not exist"
    else
    mv $dir/*.$i.log $dir/*.$next.log
    echo "moves $dir/*.$i.log to $dir/*.$next.log"
    exit
fi

done

touch $dir/*.0.log

0 个答案:

没有答案