公司服务器硬盘最近满了,
执行du -h –max-depth=1一级一级顺着目录往下找,终于发现一个目录下存在大量相似名称的文件,而且每天都有新文件产生,查看一下几乎全是运行日志,占用了将近10个GB,于是写了个脚本放在cron中定期执行。
脚本用到的一些东西:
++++++++更新+++++++
文件名称中有日期的可以直接使用date命令,与字符串截取的方法类似但要简单许多
find . -name "usercenter-service-`date +%Y-%m-%d`.*.log"
时间命令
time=$(date ‘+%Y%m%d’ )
遍历获取文件名
for file_name in `ls`
do
file_path=&file_name
done
字符串截取
file_path=${file_name:0:17}
#从“0”开始获取“17”个字符
“[]”支持 -ge,-lt等运算符
“[[]]”支持 “&&”,”||”运算符
变量运算
`expr $month – 2`
完整脚本
#!/bin/bash
cd /logs/usercenter/format_log/history
year=`date '+%Y'`
month=`date '+%m'`
day=`date '+%d'`
for file_name in `ls`
do
file_path1=${file_name:0:17}
file_path2=${file_name:0:18}
if [[ $file_path1 == usercenter-common || $file_path2 == usercenter-service ]]
then
if [ $file_path1 == usercenter-common ]
then
file_year=${file_name:18:4}
file_month=${file_name:23:2}
file_day=${file_name:26:2}
elif [ $file_path2 == usercenter-service ]
then
file_year=${file_name:19:4}
file_month=${file_name:24:2}
file_day=${file_name:27:2}
fi
if [[ $file_year -eq $year ]]
then
if [ $file_month -lt `expr $month - 2` ]
then
rm -rf $file_name
fi
if [ $file_month -eq `expr $month - 2` ]
then
if [ $file_day -le $day ]
then
rm -rf $file_name
fi
fi
fi
if [[ $file_year -lt $year ]]
then
if [ $month -ge 2 ]
then
rm -rf $file_name
elif [[ $month -eq 1 && $file_month -eq 11 ]]
then
if [[ $file_day -le $day ]]
then
rm -rf $file_name
fi
elif [[ $month -eq 1 && $file_month -lt 11 ]]
then
rm -rf $file_name
fi
fi
fi
done