伺服器上的日誌、暫存檔只增不減,遲早把磁碟吃乾。把它丟進排程器自動清理,是省下無數次半夜搶救的基本功。
cat auto_clear_file.sh
#!/bin/sh
# 各系統通用的檔案清理腳本
# 參數:filepath reg_filename fileatime
# author: Foyon0806@gmail.com
# date: 2013-8-22
if [ $# -eq 0 ]; then
echo "Usage: sh auto_clear_file.sh clear_filepath clear_regfilename filecreatetime"
echo "eg: sh auto_clear_file.sh /tmp/log/ user_log -7day"
exit
fi
filepath=$1
regfilename=$2
if [ "-$3" = "-" ]; then
filectime=`date -d -7day '+ %s'`
else
filectime=`date -d $3 '+ %s'`
fi
log=`ls $filepath | grep $regfilename`
echo $log
for file in ${log}
do
echo $file
fileatime=`stat -c %X ${filepath}${file}`
if [ ${fileatime} -lt ${filectime} ]; then
opt=`rm -f ${filepath}${file}`
echo $opt
fi
done
filepath 要清掃的目錄 regfilename 檔名比對用的關鍵字(grep 規則) fileatime 時間門檻,例如 -7day;不填預設七天
腳本用 stat -c %X 取出檔案最後存取時間的 epoch 秒數,與門檻時間戳比大小,小於門檻就刪。
crontab -e 0 3 * * * /bin/sh /usr/auto_clear_file.sh /tmp/log/ user_log -7day
每天凌晨三點清一次。
rm -f 換成 echo rm -f 試跑,確認清單無誤再改回來。${filepath}${file} 會拼出錯誤路徑。%X 換成 %Y 即可。