리눅스

[Rsync 자동화] 파일 백업 자동화 - 2

알 수 없는 사용자 2023. 8. 4. 12:26
반응형

쉘스크립트를 이용한 백업 자동화


쉘스크립트를 만들어 크론탭으로 주기적으로 백업하게 만들것이다

쉘스크립트를 자동으로 만들어주는 쉘스크립트를 만들어 Rsync가 필요한 디렉토리가 생길때 마다 편하게 쓰면 어떨까

코드.sh

 echo "Rsync Source Path :"
 read source_path

 echo "Rsync Destination Path :"
 read des_path

 echo '
 check=`diff -r source_path des_path -q -x "*.*.*"`
 if [ -n "$check" ]
 then
         addfile_src=`diff -r source_path des_path -q | grep "Files" | cut -d " " -f 2`
         addfile_des=`diff -r source_path des_path -q | grep "Files" | cut -d " " -f 4`
         addfile_num=`echo $addfile_src | wc -w`
         if [ "0" != $addfile_num ]
         then
                 for (( i=1; i<=$addfile_num; i++))
                 do
                         target_src=`echo $addfile_src | cut -d " " -f $i`
                         target_des=`echo $addfile_des | cut -d " " -f $i`
                         echo -e $i"/"$addfile_num" src:" $target_src"\t\t\tdes:" $target_des
                         rsync -r --backup --suffix=`date +'.%F_%H-%M-%S'` $target_src $target_des
                 done
         fi 

         echo "adding file rcync success"

         nonefile_dir=`diff -r source_path des_path -q | grep -v "des_path:" | cut -d ":" -f 1 | cut -d " " -f 3`
         nonefile_file=`diff -r source_path des_path -q | grep -v "des_path:" | cut -d " " -f 4`
         nonefile_num=`echo $nonefile_dir | wc -w` 

         if [ "0" != $nonefile_num ]
         then
                 for (( i=1; i<=$nonefile_num; i++))
                 do
                         target_dir=`echo $nonefile_dir | cut -d " " -f $i`
                         target_subdir="/"`echo $target_dir | tr -d "source_path"`
                         target_file="/"`echo $nonefile_file | cut -d " " -f $i`
                         target_src="source_path"${target_subdir}${target_file}
                         target_des="des_path"$target_subdir
                         echo -e $i"/"$nonefile_num "src :" $target_src"\t\t\tdes :" $target_des
                         rsync -r --backup --suffix=`date +".%F_%H-%S"` $target_src $target_des
                 done
         fi

         echo "empty file rcync success"

 fi' >> backup.sh

 sed -i "s|source_path|$source_path|g" backup.sh
 sed -i "s|des_path|$des_path|g" backup.sh

이 쉘스크립트를 실행하면 backup.sh 파일이 생성되고 이 쉘을 통해 rsync를 할 수 있다.

코드 분석은 따로 안해주겠다. 쉘을 이용하여 자신이 사용할 자동화 스크립트를 짜둔다면 매우 편리해지므로 내 코드를 가져다써도 좋지만 직접 만들어보길 바란다. 그리고 더 간단하게 구현할 수 있다면 간단하게, 효율적으로 구현하여 사용하길 바란다.

반응형