主动清理超出备份数的最老备份文件
#! /usr/bin/env bash
# 备份目录
bak_dir="../bak"
# 备份最大数量
bak_max=5
# 备份文件名固定为如下格局
# archive.tar.gz
echo -n "请输出备份版本号:"
read version
if [-f ./archive.tar.gz];then
echo "clean archive.tar.gz"
rm -rf archive.tar.gz
fi
tar -zcf archive.tar.gz ./*
if [! -d $bak_dir];then
mkdir $bak_dir
fi
bak_file="${bak_dir}/archive.${version}.tar.gz"
# 已存在备份文件 则做笼罩
if [-f $bak_file];then
rm $bak_file
fi
cp archive.tar.gz $bak_file
echo "baking success $bak_file"
# 革除老的备份
bak_cnt=$(ls -l $bak_dir | grep "^-" | wc -l)
echo "bak cnt $bak_cnt"
while (($bak_cnt > $bak_max)); do
oldest_file=$(ls -rt $bak_dir | head -1) #获取最旧的备份
echo "delete old file:"$oldest_file
rm -rf $bak_dir/$oldest_file
let "bak_cnt--"
done
echo "---- bak file list ----"
ls -l $bak_dir | egrep "^-|^d"
echo "---- bak file list ----"
可执行权限
chmod a+x bak.sh
在想要备份的文件夹下执行 ./bak.sh
即可