2017-02-23 72 views
0

我能够脚本备份过程,但我想为存储服务器创建另一个脚本以进行基本文件轮换。 我想做什么: 我想将我的文件存储在我的/ 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.tarshell备份脚本重命名

我该怎么做? 我想:

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" 
+0

您遇到的确切问题是什么? – CJxD

+0

由于某种原因,它重命名的文件是这样的: site_foo_date_2.tar site_foo_date_4.tar site_foo_date_6.tar ... 在下一个周期: site_foo_date_3.tar site_foo_date_5.tar site_foo_date_7.tar 所以每第二个数字是失踪,我不不知道为什么。 – kesien

+0

对我来说工作得很好 - 我要做的只是通过解释来制作一个更具韧性的代码版本 – CJxD

回答

0

与您的代码的主要问题是,通过与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 
+0

谢谢!有用 ! :) – kesien