#删除指定目录下创建日期大于30天的.log .txt文件(如果目录下文件总数少于10个,就不删除),删除的文件记录写入到日志
#!/bin/bash
#待删除的文件路径数组,多个目录换行
locations=(
/root/logs/web1/
/root/logs/web2/
/root/logs/web3/
)
#输出的文件路径
myfile=/root/java/delLogFile_Logs.txt
#当前时间now Time
nowTime="`date +%Y-%m-%d,%H:%m:%s`"
#写入删除日志文件
echo "====================Task Time:${nowTime}=================" >> ${myfile}
#循环路径
for ((j = 0; j < ${#locations[*]}; j = j+ 1))
do
#具体路径
location=${locations[$j]}
echo '========================================================'
echo 'Begin Delete Path['$j']:' $location
fileCount=$(find $location -maxdepth 1 -print | wc -l) #过滤文件创建超过30天的
file=`find $location -maxdepth 1 -mtime +30 -print`
echo 'All File Count:' $fileCount
#echo $file
deleteCount=0
#文件总数大于10才删除
if [ $fileCount -gt 10 ]
then
for i in $file
do
#待删除文件的格式.log .txt
if [ "${i##*.}"x = "log"x ]||[ "${i##*.}"x = "txt"x ]
then
time1=$(date "+%Y-%m-%d %H:%M:%S")
echo 'OK Delete CreateTime:'${time1} ' File:' ${i}
#写入删除日志文件
echo "Delete Time:${nowTime},File:${i}" >> ${myfile}
#删除文件
rm -r $i
deleteCount=$(($deleteCount+1))
else
echo 'not Delete File:' ${i}
fi
done
else
echo 'not any file delete'
fi
echo 'Delete File Count:' $deleteCount
done
echo "===============Task complete======================="
#vi /etc/crontab
59 11 28 * * root /root/del-30.sh 每月的28日11点59执行
:wq
#service crond restart
评论区