脚本适用于linux服务器各种场景下的文件清理,这里以zk为例,其他场景类似。
清理逻辑:当某磁盘空间使用率高于70%的时候,保留目标目录下50个最新文件,删除其他文件。
#!/bin/bash
#设置保留个数
retainSnapCount=50
retainLogCount=50
#获取磁盘使用率
usePercent=$(df -h /mydir/ | grep "/mydir" | awk '{print $5}' | awk -F'%' '{print $1}')
#获取目标目录当前文件个数
snapshotCount=$(/bin/find /mydir/data/zookeeper/version-2/ -name 'snapshot.*' -type f | wc -l)
logCount=$(/bin/find /mydir/log/zookeeper/version-2/ -name 'log.*' -type f | wc -l)
#计算删除的文件个数
delSnapCount=$((snapshotCount-retainSnapCount))
delLogCount=$((logCount-retainLogCount))
#获取删除的文件列表
fDelData()
{
/bin/find /mydir/data/zookeeper/version-2/ -name 'snapshot.*' -type f | xargs ls -t | tail -$delSnapCount > /tmp/zkDelFile.txt
# /bin/find /mydir/data/zookeeper/version-2/ -name 'snapshot.*' -type f | xargs ls -t | tail -$delSnapCount | xargs /bin/rm -f
}
#获取删除的文件列表
fDelLog()
{
/bin/find /mydir/log/zookeeper/version-2/ -name 'log.*' -type f | xargs ls -t | tail -$delLogCount >> /tmp/zkDelFile.txt
# /bin/find /mydir/log/zookeeper/version-2/ -name 'log.*' -type f | xargs ls -t | tail -$delLogCount | xargs /bin/rm -f
}
#删除文件
delFile(){
while read file ; do rm -f $file ; done < /tmp/zkDelFile.txt
}
if [ $usePercent -gt "70" ]
then
fDelData
fDelLog
delFile
else
now=$(date "+%Y-%m-%d %H:%M:%S")
echo "$now Nothing to do..." >> /tmp/zkClear.log
exit 0
fi