shell實現日誌滾動

什麼是日誌滾動?

在日常linux的操作中,經常會產生各種各樣的日誌文件,如果不加以處理,經常會導致單個日誌文件體積過於臃腫,不利於後期排查。因此需要對日誌文件定期操作,比如每天將日誌文件打包備份,重新編排版本號等。linux發行版中也默認安裝了logrotate這款上古神器來管理日誌,它可以自動對日誌進行截斷(或輪循)、壓縮以及刪除舊的日誌文件。

但是這裏並不想去過多介紹logrotate這款工具,而是着重於自己編寫shell腳本去實現類似的功能。

實現思路

  • 如果日誌文件沒有數字後綴,那麼添加數字後綴;
  • 如果日誌文件已經有數字後綴,那麼查看數字後綴是否小於11;
  • 如果日誌文件數字後綴小於11,那麼將日誌文件數字後綴加1;
  • 如果日誌文件數字後綴大於等於11,那麼保持不變或者等待數字後綴爲10的日誌文件覆蓋它。

執行過程

核心代碼實現

for item in $list; do
    local suffix=${item##*.}
    local prefix=${item%.*}
    expr $(($suffix+0)) 2>&1 > /dev/null
    if [ $? -eq 0 ]; then
        if [ $suffix -lt 11 ]; then
            suffix=$(($suffix+1))
            mv $item $prefix.$suffix
        fi
    else
        mv $item $prefix.$suffix.1
    fi
done

實現效果

[hadoop@li-pc ~]$ mkdir haha
[hadoop@li-pc ~]$ touch haha/{a..d}.log e.log.11
[hadoop@li-pc ~]$ ls haha
a.log  b.log  c.log  d.log  e.log.11
[hadoop@li-pc ~]$ ./shell.sh; ls haha
a.log.1  b.log.1  c.log.1  d.log.1  e.log.11
[hadoop@li-pc ~]$ ./shell.sh; ls haha 
a.log.2  b.log.2  c.log.2  d.log.2  e.log.11

附件

#!/bin/bash

move_file() {
    list=$@
    for item in $list; do
        local suffix=${item##*.}
        local prefix=${item%.*}
        expr $(($suffix+0)) 2>&1 > /dev/null
        if [ $? -eq 0 ]; then
            if [ $suffix -lt 11 ]; then
                suffix=$(($suffix+1))
                mv $item $prefix.$suffix
            fi
        else
            mv $item $prefix.$suffix.1
        fi
    done
}

is_exisit() {
    if [ -d $1 ]; then
        return 0
    fi  
    return 1
}

main() {
    is_exisit $1
    if [ $? -eq 0 ]; then
        cd $1
        list=$(ls | sort -r)
        move_file $list
    else
        echo "The direcotry - $path - is not existed!"
    fi
}

path="/home/hadoop/haha"
main $path
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章