1 #!/bin/bash 2 #统计一周时间内的日志总大小,清空达到2G的log并计数 3 4 #dir="/home/parastor/log" #目录格式最后不加/ 5 dir="/var/log" 6 let maxsize=2*1024*1024*1024 #日志大小的最大值2G,单位B 7 let maxsizeG=2 #日志大小的最大值2G,单位GB 8 let aWeek=7*24*3600 #一周多少秒 9 startTime=$(date +%s) 10 count=0 11 12 #子函数遍历文件夹及其子文件夹 13 function getdir() 14 { 15 for element in `ls $1` 16 do 17 file=$1"/"$element 18 if [ -d $file ] 19 then 20 getdir $file 21 else 22 echo $file 1>> dir.out #将结果保存到dir.out 23 fi 24 done 25 } 26 27 while true 28 do 29 nowTime=$(date +%s) 30 let diffTime=nowTime-startTime 31 if [ "$diffTime" -lt "$aWeek" ] 32 then 33 echo > dir.out #清空文件内容 34 getdir $dir #引用子函数得到所有文件路径 35 for line in `cat dir.out` #遍历dir.out每行 36 do 37 filesize=`ls -l $line | awk '{ print $5 }'` #得到文件大小 38 if [ "$filesize" -ge "$maxsize" ] 39 then 40 echo > $line 41 printTime=$(date +%Y%m%d-%H:%M:%S) 42 echo -e "$printTime $line is emptied " >> emptyLog.out #记录被清空的日志和时间 43 let count++ 44 fi 45 done 46 sleep 1 47 else 48 startTime=$nowTime 49 let totalSize=maxsizeG*count 50 printTime=$(date +%Y%m%d-%H:%M:%S) 51 echo -e "$printTime The total logsize of a week is $totalSize GB " >> totalLogSize.out 52 count=0 53 fi 54 done