Linux 下有許多備份工具。 我選擇的是 dar ,因爲我感覺它最方便,它其實就是一個打包工具,類似tar,但支持分卷, 差異備份等功能, 恢復數據也很方便。 這是我寫的一個備份Home目錄的方法。
#! /bin/bash
# using `dar' to backup a whole directory. There're two methods here:
# full backup and diff backup
# Dai Yuwen
# 4 Dec, 2010, initial version
# typical full backup
#dar -v -c /tmp/nfs/home_full -s 2000M -z -R /home/yuwen -P .VirtualBox -P .thumbnails -P .ccache
# typical diff backup
#dar -v -c /mnt/wd2/yuwen/home_diff5 -A /mnt/wd2/yuwen/home_full -R /home/yuwen -s 2000M -z -P .VirtualBox -P .thumbnails -P .ccache
Usage ()
{
echo "Options:"
echo "-h print this help"
echo "-e dry run"
echo "-f <file name> full backup"
echo "-d <reference file> diff backup base on reference file"
echo
echo "Examples:"
echo "backup.sh [-e] -f <file name>"
echo "backup.sh [-e] -d <reference file>"
}
# parse the options by using getopt
TEMP=`getopt -o ehf:d: -n 'backup.sh' -- "$@"`
# parse error
if [ $? != 0 ]; then
Usage >&2 ;
exit 1 ;
fi
eval set -- "$TEMP"
DRY_RUN=""
FULL=""
DIFF=""
while true; do
case "$1" in
-e) DRY_RUN=" -e ";shift;;
-h) Usage >&2; exit 0;;
-f) NAME="$2";FULL="y"; shift 2;;
-d) REF="$2";DIFF="y";shift 2;;
--) shift; break;;
esac
done
# full backup and diff backup are exclusive
# check the options
if [ "$FULL" == "y" -a "$DIFF" == "y" ]; then
echo full backup and diff backup are exclusive
exit 1
fi
if [ "$FULL" == "" -a "$DIFF" == "" ]; then
echo You must specify -f or -d option
Usage >&2 ;
exit 1
fi
#
# Customized options that you can modify
#
# the BASE dir
BASE=/home/yuwen
# add your excluded files here
EXC_FILES=".VirtualBox .thumbnails .ccache tmp .cache .tmp English Videos"
# other options for dar
OTHER_OPTIONS=" -v -s 2000M -z "
#
# End of customized options
#
# the timestamp in the file name
DATA=`date +%Y%m%d`
# compose the options
EXC_OPT=""
for i in $EXC_FILES; do
EXC_OPT=" -P $i $EXC_OPT"
done
# full backup
if [ "$FULL" == "y" ]; then
eval dar $DRY_RUN -c "$NAME"_"$DATA" -R $BASE $OTHER_OPTIONS $EXC_OPT
fi
# diff backup
if [ "$DIFF" == "y" ]; then
eval dar $DRY_RUN -c "$REF"_diff_"$DATA" -A "$REF" -R $BASE $OTHER_OPTIONS $EXC_OPT
fi
如果你要使用,請修改腳本中的幾個變量, BASE 指定的是home目錄的名字,請替換成你自己的目錄名, EXC_FILES 是不想備份的目錄, 請按自己的需要來寫。 OTHER_OPTIONS 指定的分卷文件的尺寸是2000M, 是爲了防止某些文件系統不支持2G以上的大文件,可以根據自己的需要修改。
接上一個USB硬盤,就可以備份了。 第一次備份先做一個全備份:
~/bin/backup.sh -f /mnt/usb/my_home
如果你很謹慎, 想看一下它會備份哪些目錄, 可以先做一次 dry run:
~/bin/backup.sh -e -f /mnt/usb/my_home
dar生成的文件默認後綴是dar,你不需要指定後綴,只要寫文件的基本名。 腳本會在生成的文件名後面添加日期。 以後的備件可以基於上一次的全備份,作一個差異備份:
~/bin/backup.sh -d /mnt/usb/my_home-<date>
它表示用 my_home-<date> 做基準, 做一個差異備份。