問(wèn)題描述
程序每天在/var/www/storage/log目錄下生產(chǎn)日志量九,日志按照日期存儲(chǔ)泉瞻,比如2017-05-16的日志雕沉,就存儲(chǔ)在/var/www/storage/log/20170516下企软,以此類推。每天的日志大致有兩類借笙,文件名中有tmp標(biāo)識(shí)表示可以刪除储笑,有forever標(biāo)識(shí)的表示不可以刪除孕暇。當(dāng)磁盤(pán)使用率達(dá)到80%,則要?jiǎng)h除日志tmp標(biāo)識(shí)的日志只搁,以此降低磁盤(pán)使用率∫舯龋現(xiàn)在我們讓問(wèn)題變得更具體。
已知在/var/www/storage/log(目錄掛在/dev/vdb1下)有20170516氢惋,20170517洞翩,20170518三個(gè)日志目錄,每個(gè)目錄下各有1-tmp.log明肮、2-tmp.log菱农、forever.log三個(gè)日志文件缭付。當(dāng)日志文件所在磁盤(pán)使用率大于80%時(shí)柿估,需要按日期小到大按天刪除帶有tmp的日志文件,直到磁盤(pán)使用率小于80%陷猫。
解答思路
為了解答這個(gè)問(wèn)題秫舌,我們需要知道/dev/vdb1當(dāng)前是使用率。df -hl | grep /dev/vdb1 | awk '{print $5}
這個(gè)命令的意思是绣檬,在df -hl的結(jié)果中找出含有/dev/vdb1的那個(gè)足陨,并輸出第5個(gè)參數(shù)。也就是磁盤(pán)使用的百分比娇未。由于我們會(huì)重復(fù)判斷磁盤(pán)使用率是否超過(guò)了80%墨缘,所以是否超過(guò)80%的邏輯,可以寫(xiě)成函數(shù)零抬。
function is_not_overusage(){
limit_useage=$1
useage=$(df -hl | grep /dev/vdb1 | awk '{print $5}')
useage=${useage//%/}
echo "current $useage"
if [ $useage -lt $limit_useage ]
then
return 1
else
return 0
fi
}
那我們?nèi)绾蝿h除指定目錄下的帶有tmp的文件啦,執(zhí)行:
rm -rf `ls | egrep '(tmp){1}'
這里的正則寫(xiě)的比較簡(jiǎn)單镊讼,如果誤刪除了文件,請(qǐng)自行修改正則表達(dá)式平夜。
示例代碼
#!/bin/bash
function is_not_overusage(){
limit_useage=$1
useage=$(df -hl | grep /dev/vdb1 | awk '{print $5}')
useage=${useage//%/}
echo "current $useage"
if [ $useage -lt $limit_useage ]
then
return 1
else
return 0
fi
}
function clearlog(){
echo "delete $1"
fileinfo=$(cd $1;rm -rf `ls | egrep '(tmp){1}'`)
}
limit_useage=80
is_not_overusage $limit_useage
if [ $? -eq 1 ]
then
echo 'nothing needs to do'
exit
fi
log_storage="/data/www/storage/logs"
for element in `ls $log_storage`
do
dir_or_file=$log_storage"/"$element
if [ -d $dir_or_file ]
then
clearlog $dir_or_file
is_not_overusage $limit_useage
if [ $? -eq 1 ]
then
exit
fi
fi
done