2017-02-23 6 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이 가장 ​​최근의 백업 파일입니다. 지난 10 일 동안 파일이 삭제됩니다. 다른 서버의 들어오는 파일의 이름은 다음과 같습니다. 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" 
+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

관련 문제