工作需要,写了备份和恢复文件的脚本:
conf 文件:要备份和恢复的文件列表,支持正则,以 # 开头的为注释
bak.sh 文件:读取 conf 文件,并备份所有文件到当前目录的 files 目录中(需要更改你自己的 $HOME 目录,如果需要,更改你喜欢的拷贝命令,默认 rsync)
restore.sh 文件:读取 conf 文件,并将 files 目录中的文件按 conf 文件恢复(需要更改你自己的 $HOME 目录,如果需要,更改你喜欢的拷贝命令,默认 rsync)
所有文件已经上传至百度云:http://pan.baidu.com/s/1gdECx95
bak.sh
1 #!/bin/sh 2 # Author lian 3 HOME="/home/lian" 4 conf="./conf" 5 dest_dir="./files" 6 #copy="cp -rpv" 7 #copy="rsync -avzPSH" 8 copy="rsync -avPSH --delete" 9 #copy="echo" 10 11 # calculate the total size 12 size=$( 13 sed -n -e "/^#/!p" $conf | 14 while read file 15 do 16 du -sb `eval echo $file` 17 done | awk 'BEGIN{sum=0} {sum+=$1} END{print sum}' 18 ) 19 #echo "Total size: $(($size/1024/1024)) MB" 20 # more accurate 21 echo "Total size: `echo "scale=4; $size/1024/1024" | bc` MB" 22 23 # now copy 24 if [ ! -d $dest_dir ] 25 then 26 mkdir $dest_dir 27 fi 28 29 :<<\EOF 30 if [ -d $dest_dir ] 31 then 32 sudo rm -fr $dest_dir 33 mkdir $dest_dir 34 else 35 mkdir $dest_dir 36 fi 37 EOF 38 39 sed -n -e "/^#/!p" $conf | 40 while read file 41 do 42 eval echo $file 43 done | awk '{for(i=1; i<=NF; i++) print $i}' | xargs -i sudo $copy {} $dest_dir 44 45 echo `du -sh | awk '{print "Total copied size: " $1}'`
restore.sh
1 #!/bin/sh 2 # Author lian 3 HOME="/home/lian" 4 conf="./conf" 5 src_dir="./files" 6 #copy="cp -rpv" 7 #copy="rsync -avzPSH" 8 copy="rsync -avPSH --delete" 9 #copy="echo" 10 11 # now restore 12 sed -n -e "/^#/!p" $conf | awk -F/ '{ 13 dir_name=$1 14 for(i=2; i<NF; i++) 15 { 16 dir_name=dir_name"/"$i 17 } 18 print dir_name":"$NF 19 }' | 20 while read file 21 do 22 #dir_name=`dirname $file` 23 #dir_name=`echo "$file" | awk -F/ 'BEGIN{dir_name=$1}{for(i=1; i<NF; i++){print i,$i}}END{print dir_name}'` 24 dir_name=$(eval echo `echo "$file" | awk -F: '{print $1}'`) 25 file_name=`echo "$file" | awk -F: '{print $2}'` 26 #echo $dir_name 27 eval echo $src_dir/$file_name | 28 awk '{ 29 for(i=1; i<=NF; i++) 30 { 31 cmd="echo "$i" | xargs -i basename {}"; 32 cmd | getline var; 33 print var; 34 } 35 }' | 36 xargs -i echo "$copy $src_dir/{} $dir_name" | 37 sh 38 done 39 40 echo "Total restored size: `du -sh $src_dir`"
我的 conf 文件:
# files needed to bak $HOME/.bash* $HOME/bin $HOME/.config $HOME/.dropbox* $HOME/.eclipse $HOME/.fontconfig $HOME/.getmail $HOME/.i3* $HOME/Life $HOME/Mails $HOME/.mplayer $HOME/.rtorrent.rc $HOME/.shutter $HOME/.spf13-vim-3 $HOME/.sunpinyin $HOME/.thunderbird $HOME/.tmux.conf $HOME/.vim* $HOME/.virtinst $HOME/.virt-manager $HOME/.w3m $HOME/WorkDir $HOME/workspace $HOME/.[xX]* /etc/httpd /etc/my.cnf* /etc/php* /etc/rsync* /etc/samba /etc/vsftpd /etc/hosts