shell脚本实现sh自动删除清理指定过期日期备份功能
本脚本具体功能,请看脚本中备注的地方,前提条件,比如/backup/mybk下面的目录是年月日格式,比如:20200801(我的备份目录中,还有一个now文件夹也保留),大家可以自行修改为自己的代码,免费拿走。
#!/bin/bash
ROOT_UID=0
E_NOTROOT=67
if [ "$UID" -ne "$ROOT_UID" ]
then
echo "Must be root to run this script"
exit $E_NOTROT
fi
#配置需要操作的备份目录
backupDir=/backup/mybk
:<<!
#本脚本可以实现:(假设当前月是202008)
#保留当前备份文件夹now
#保留当前月备份文件夹:202008
#保留当前月后3个月备份文件夹:202007+202006+202005
#保留当前月后9个月备份文件夹中日期最大的一份(删除其他):202004+202003+202002+202001+201912+201911+201910+201909+201908
!
function arrDelete(){
#把传递过来的数组作为arr
arr=$1
#找出数组中的最大值,初始值为0
MAX=0
for v in ${arr[@]}
do
if [[ $MAX -le $v ]]
then
MAX=$v
fi
done
#再循环一遍,比较大小,找到应该删除的文件夹
for v in ${arr[@]}
do
if [[ $MAX -ne $v ]]
then
echo "不是当月最大,删除:"$backupDir"/"$v
rm -rf $backupDir"/"$v
fi
done
}
function read_dir(){
monthAgo0=$(date +%Y%m)
monthAgo1=$(date "-d 1 month ago" +%Y%m)
monthAgo2=$(date "-d 2 month ago" +%Y%m)
monthAgo3=$(date "-d 3 month ago" +%Y%m)
monthAgo4=$(date "-d 4 month ago" +%Y%m)
monthAgo5=$(date "-d 5 month ago" +%Y%m)
monthAgo6=$(date "-d 6 month ago" +%Y%m)
monthAgo7=$(date "-d 7 month ago" +%Y%m)
monthAgo8=$(date "-d 8 month ago" +%Y%m)
monthAgo9=$(date "-d 9 month ago" +%Y%m)
monthAgo10=$(date "-d 10 month ago" +%Y%m)
monthAgo11=$(date "-d 11 month ago" +%Y%m)
monthAgo12=$(date "-d 12 month ago" +%Y%m)
for file in `ls $1` #注意此处这是两个反引号,表示运行系统命令
do
if [ -d $1"/"$file ] #注意此处之间一定要加上空格,否则会报错
then
if [[ $file == *now* ]]
then
echo "now,保留全部:"$1"/"$file
elif [[ $file == *$monthAgo0* ]]
then
echo "当月,保留全部:"$1"/"$file
elif [[ $file == *$monthAgo1* ]] || [[ $file == *$monthAgo2* ]] || [[ $file == *$monthAgo3* ]]
then
echo "最近3个月,保留全部:"$1"/"$file
elif [[ $file == *$monthAgo4* ]]
then
arrmonthAgo4[${#arrmonthAgo4[@]}]=$file
elif [[ $file == *$monthAgo5* ]]
then
arrmonthAgo5[${#arrmonthAgo5[@]}]=$file
elif [[ $file == *$monthAgo6* ]]
then
arrmonthAgo6[${#arrmonthAgo6[@]}]=$file
elif [[ $file == *$monthAgo7* ]]
then
arrmonthAgo7[${#arrmonthAgo7[@]}]=$file
elif [[ $file == *$monthAgo8* ]]
then
arrmonthAgo8[${#arrmonthAgo8[@]}]=$file
elif [[ $file == *$monthAgo9* ]]
then
arrmonthAgo9[${#arrmonthAgo9[@]}]=$file
elif [[ $file == *$monthAgo10* ]]
then
arrmonthAgo10[${#arrmonthAgo10[@]}]=$file
elif [[ $file == *$monthAgo11* ]]
then
arrmonthAgo11[${#arrmonthAgo11[@]}]=$file
elif [[ $file == *$monthAgo12* ]]
then
arrmonthAgo12[${#arrmonthAgo12[@]}]=$file
else
echo "超过12个月,删除:"$1"/"$file
rm -rf $1"/"$file
fi
else
echo "is file,skip:"$1"/"$file
fi
done
#循环各个数组,删除其中不是最大的一个文件夹
#注意:传递数组为参数,必须要用引号扩起来,否则只能获取到第一个下标
arrDelete "${arrmonthAgo4[*]}"
arrDelete "${arrmonthAgo5[*]}"
arrDelete "${arrmonthAgo6[*]}"
arrDelete "${arrmonthAgo7[*]}"
arrDelete "${arrmonthAgo8[*]}"
arrDelete "${arrmonthAgo9[*]}"
arrDelete "${arrmonthAgo10[*]}"
arrDelete "${arrmonthAgo11[*]}"
arrDelete "${arrmonthAgo12[*]}"
}
#遍历备份目录并操作
read_dir $backupDir
近期评论