shell 备份脚本重命名

shell backup script renaming

我能够编写备份过程的脚本,但我想为我的存储服务器制作另一个脚本来进行基本的文件轮换。 我想做什么: 我想将我的文件存储在我的 /home/user/backup 文件夹中。只想存储 10 个最新鲜的备份文件并将它们命名为: site_foo_date_1.tar site_foo_date_2.tar ... site_foo_date_10.tar site_foo_date_1.tar 是最新的备份文件。 超过 num10 文件将被删除。 我从其他服务器传入的文件简单地命名为:site_foo_date.tar

我该怎么做? 我试过了:

DATE=`date "+%Y%m%d"`


cd /home/user/backup/com
if [ -f site_com_*_10.tar ]
then
rm site_com_*_10.tar
fi

FILES=$(ls)

for file in $FILES
do
echo "$file"
if [ "$file" != "site_com_${DATE}.tar" ]
then
str_new=${file:18:1}
new_str=$((str_new + 1))
to_rename=${file::18} 
mv "${file}" "$to_rename$new_str.tar" 
fi
done

file=$(ls | grep site_com_${DATE}.tar)
filename=`echo "$file" | cut -d'.' -f1`
mv "${file}" "${filename}_1.tar"

您的代码的主要问题是,在没有某种过滤器的情况下使用 ls * 循环遍历目录中的所有文件是一件危险的事情。

相反,我使用 for i in $(seq 9 -1 1) 循环遍历从 *_9 到 *_1 的文件以移动它们。这确保我们只移动备份文件,而不会移动任何其他可能意外进入备份目录的文件。

另外,靠序号是文件名中的第18个字符也是注定要破的。如果您以后想要超过 10 个备份,会发生什么情况?通过这种设计,您可以将 9 更改为您喜欢的任何数字,即使它超过 2 位数。

最后,我在移动之前添加了一个检查 site_com_${DATE}.tar 以防它不存在。

#!/bin/bash

DATE=`date "+%Y%m%d"`

cd "/home/user/backup/com"
if [ -f "site_com_*_10.tar" ]
then
rm "site_com_*_10.tar"
fi

# Instead of wildcarding all files in the directory
# this method picks out only the expected files so non-backup
# files are not changed. The renumbering is also made easier
# this way.
# Loop through from 9 to 1 in descending order otherwise
# the same file will be moved on each iteration
for i in $(seq 9 -1 1)
do
# Find and expand the requested file
file=$(find . -maxdepth 1 -name "site_com_*_${i}.tar")
if [ -f "$file" ]
then
echo "$file"
# Create new file name
new_str=$((i + 1))
to_rename=${file%_${i}.tar}
mv "${file}" "${to_rename}_${new_str}.tar" 
fi
done

# Check for latest backup file
# and only move it if it exists.
file=site_com_${DATE}.tar
if [ -f $file ]
then
filename=${file%.tar}
mv "${file}" "${filename}_1.tar"
fi