直接上代碼,注意shell格式很重要:
#!/bin/bash
#删除5天以前的日志資料 日志位于./logs 檔案夾下
find ./logs/ -mtime + -name "*.log*" -exec rm -rf {} \;
#需要保留7天的資料的檔案夾名
FileDir7=(drama homepage weibo weixin )
#需要保留20天的資料的檔案夾名
FileDir20=(competitor douban omit)
start=$(date +%y-%m-%d)
#該sh腳本産生的日志
File=./logs/log-dellogfile.log.$start
#資料存儲檔案夾
FilePath=./output_data/
#如果檔案夾不存在容易報錯且誤删資料
if [ ! -d $FilePath ]; then
mkdir $FilePath
fi
for dir in "${FileDir7[@]}"; do
FilePathTemp=${FilePath}${dir}
#如果檔案夾不存在容易報錯且誤删資料 非常重要 一定要建立檔案夾 空的也無所謂 不占空間
if [ ! -d $FilePathTemp ]; then
mkdir $FilePathTemp
fi
done
for dir in "${FileDir20[@]}"; do
FilePathTemp=${FilePath}${dir}
if [ ! -d $FilePathTemp ]; then
mkdir $FilePathTemp
fi
done
for dir in $(ls $FilePath); do
for filename in "${FileDir7[@]}"; do
if [ $filename = $dir ]; then
FilePathTemp=${FilePath}${filename}
echo $FilePathTemp >> $File
day=
echo "find $FilePathTemp -type d -mtime +$day > $File" >> $File
find $FilePathTemp -type d -mtime +$day >> $File
echo "find $FilePathTemp -type d -mtime +$day | xargs rm -rf" >> $File
find $FilePathTemp -type d -mtime +$day | xargs rm -rf
fi
done
for filename in "${FileDir20[@]}"; do
if [ $filename = $dir ]; then
FilePathTemp=${FilePath}${filename}
echo $FilePathTemp >> $File
day=
echo "find $FilePathTemp -type d -mtime +$day > $File" >> $File
find $FilePathTemp -type d -mtime +$day >> $File
echo "find $FilePathTemp -type d -mtime +$day | xargs rm -rf" >> $File
find $FilePathTemp -type d -mtime +$day | xargs rm -rf
fi
done
done