linux自动删除最旧的几个文件详解





统计目录下的文件夹数量
ls -l | grep ‘^d’ | wc -l
这里的grep ‘^d’是统计文件夹,如果统计文件数目,用grep ‘^-‘
列举最老的2个文件
ls -tr | head -2 | xargs
删除所有文件
rm -rf *
完工

#!/bin/bash
#不同的项目有不同的路径
array[0]=’project1′
array[1]=’project2′
array[2]=’com/project3′
array[3]=’com/phase/project4′
array[4]=’project5′
array[5]=’com/stor/sproject6’
#项目的主干目录是相同的
RELEASE=”/opt/devapps/nexus/sonatype-work/nexus/storage/release/”

for path in ${array[@]};
do
#拼接文件路径
releasepath=${RELEASE}${path}
cd $releasepath
#判断是否存在该目录
if [ $? -eq 0 ];
then
echo $releasepath
echo “Contains file:”
#输出所有的内容
echo *
num=`ls -l | grep ‘^d’ | wc -l`;
#判断文件夹的数量是否超过5个(我只想保留最新的5个文件夹)
if [$num -gt 5 ];
then
#计算超过5个多少
num=`expr $num – 5`
clean=`ls -tr | head -$num | xargs`
echo “will delete file:”
echo ${clean}
#-n1 每次处理1个文件
ls -tr | head -$num | xargs -i -n1 rm -rf {}
fi
fi
done
完善

实际部署时,觉得直接删除文件不妥,应该是先备份到某一目录,再次运行脚本的时候,删除上次备份的文件。

#!/bin/bash
array[0]=’project1′
array[1]=’project2′
array[2]=’com/project3′
array[3]=’com/phase/project4′
array[4]=’project5′
array[5]=’com/stor/sproject6′
RELEASE=”/opt/devapps/nexus/sonatype-work/nexus/storage/release/”

#清空备份文件
BACKUP=”/tmp/storage/”
cd $BACKUP
if [ $? -eq 0 ];
then
rm -rf *
fi

#清除超过5个文件之外最老的那些文件
for path in ${array[@]};
do
releasepath=${RELEASE}${path}
cd $releasepath
if [ $? -eq 0 ];
then
echo $releasepath
echo “Contains file:”
echo *
num=`ls -l | grep ‘^d’ | wc -l`;
if [$num -gt 5 ];
then
num=`expr $num – 5`
clean=`ls -tr | head -$num | xargs`
echo “will delete file:”
echo ${clean}
#把文件移动到备份文件夹更安全
ls -tr | head -$num | xargs -i -n1 mv {} $BACKUP
fi
fi
done
自动化处理

将上述脚本保存为removecode.sh,然后添加crontab。

crontab -e
添加如下一行,每月运行一次:

0 0 1 * * /opt/project/removecode.sh > /opt/project/remove.log 2>&1 &