標籤:crontab shell compress tar
1、日誌結構/opt/online/{123com,abccom}/log/online[1-9]/[a-z]2、變數說明#是否開啟壓縮功能(0:關閉,1:開啟;若關閉壓縮功能,則compressdayn無效)needcompress=1刪除14天以前的日誌deldayn=14前1天lastdayn=1服務類型allsvrtype="online1 online2 online3"壓縮5天前的日誌compressdayn=53、計劃任務使用方法:將該指令碼本身copy到/opt/online下;crontab中配置成:#30 0 * * * cd /opt/online && chmod +x cleanlog.sh && ./cleanlog.sh >/dev/null 2>&1cat cleanlog.sh#!/bin/bash#-------------------------------------------------- #Created:2015-05-18#Author:jimmygong#Mail:[email protected]#Function:#Version:1.0#--------------------------------------------------allsvrtype="online1 online2 online3"deldayn=14needcompress=1compressdayn=5lastdayn=1alldomain="123com abccom"allsubdir="a b c d e f g h i j k l m n o p q r s t u v w x y z"rootdir="/opt/online"dirtobedelname="tobedel"lastday=`date -d "$lastdayn days ago" +%Y%m%d`compressday=`date -d "$compressdayn days ago" +%Y%m%d`delday=`date -d "$deldayn days ago" +%Y%m%d`function cleandir (){ local ldir="$1" local lfiles= local lfile= lfiles=`ls -1 $ldir | xargs` for lfile in $lfiles do rm -f $ldir/$lfile done}function compressdir (){ local ldir="$1" local lfiles= local lfile= local lcompressedtarget="$ldir/$compressday.tar.gz" # to prevent duplicate-compress if [[ -f $lcompressedtarget ]] then return fi tar zcvf $ldir.tar.gz $ldir if [[ $? -ne 0 ]] ; then return fi lfiles=`ls -1 $ldir | xargs` for lfile in $lfiles do rm -f $ldir/$lfile done if [[ -f $ldir.tar.gz ]] ; then mv $ldir.tar.gz $lcompressedtarget fi}function handleonelogdir (){ local ldir="$1" local lscandir="$ldir/$dirtobedelname" local lmvdir="$lscandir/$lastday" local lones= local lone= local lonefull= mkdir -p $lscandir # remove lones=`ls -1 $lscandir | grep $delday | xargs` for lone in $lones do lonefull="$lscandir/$lone" if [[ -d $lonefull ]] ; then cleandir $lonefull rm -rf $lonefull elif [[ -f $lonefull ]] ; then rm -f $lonefull fi done # compress if [[ $needcompress -eq 1 ]] then lones=`ls -1 $lscandir | grep $compressday | xargs` for lone in $lones do lonefull="$lscandir/$lone" if [[ -d $lonefull ]] then compressdir $lonefull elif [[ -f $lonefull ]] then tar zcvf $lonefull.tar.gz $lonefull fi done fi # move last day‘s data mkdir -p $lmvdir lones=`ls -1 $ldir | grep $lastday | xargs` for lone in $lones do mv $ldir/$lone $lmvdir done}for domain in $alldomaindo domaindir="$rootdir/$domain" if [[ ! -d $domaindir ]] then continue fi for svrtp in $allsvrtype do svrtplogdir="$domaindir/log/$svrtp" if [[ ! -d $svrtplogdir ]] then continue fi for sub in $allsubdir do svrtplogsubdir="$svrtplogdir/$sub" if [[ ! -d $svrtplogsubdir ]] then continue fi handleonelogdir "$svrtplogsubdir" done donedoneexit 0
本文出自 “7928217” 部落格,請務必保留此出處http://7938217.blog.51cto.com/7928217/1652898
shell指令碼日誌清理和壓縮