当文件夹下的文件数据达到阈值时执行删除操作,保留固定数量的文件,以此保证服务器的存储健康。
- shell脚本如下
#!/bin/bash
filepath="$1"
echo "${filepath}"
for line in $(ls -lrt ${filepath} |grep log|awk '{print $9}')
do
name[${i}]=$line
let i=${i}+1
done
listsize=${#name[@]}
echo "${listsize}"
n=0
if [ 30 -lt ${listsize} ]; then
echo "日志文件已超过30个,开始执行清理"
for line in "${name[@]}"
do
shengxia=$(($listsize-$n))
if [ ${shengxia} -gt 30 ]; then
echo "即将删除${line}"
$(rm -rf ${filepath}/${line})
fi
n=$(($n+1))
done
fi
- 脚本执行,假设脚本叫做
clean_log.sh
,路径在/root
下
sh /root/clean_log.sh /opt/apps/logs
当文件夹下个别文件大小超过xxG时执行清空命令
- shell脚本如下
#!/bin/bash
filepath="$1"
filesize="$2"
date=`date +%Y-%m-%d/%H:%M:%S`
echo ${date}" 入参"${filepath}"文件大小限制"${filesize}
for line in $(du -sh ${filepath} |grep "G"|awk -F "G" '$1>"${filesize}" {print $2}')
do
echo "文件"${line}"超过"${filesize}"G开始清理"
$(echo "" > $line)
echo "文件清理完毕"
done
- 脚本执行
auto_del_log.sh "/opt/apache-tomcat-9.0.33/logs/catalina.out" 30
- crontab 配置每天凌晨1点执行,清理两种数据:
/opt/nginx/logs/
目录所有超过100G的文件,``/opt/apache-tomcat-9.0.33/logs/catalina.out"此文件超过30G时执行清理
0 1 * * * sudo sh /opt/auto_del_log.sh "/opt/nginx/logs/*" 100 >>/opt/auto_del.log
0 1 * * * sudo sh /opt/auto_del_log.sh "/opt/apache-tomcat-9.0.33/logs/catalina.out" 30 >>/opt/auto_del.log