2012年8月29日 星期三

[Shell Script] 備份檔案

凌晨12:40
備份用

耶,就隨意寫一個shell script搭配crontab

備份自己server上的一些東西...(茶)


程式碼部分
#/bin/bash
# ./backup.sh -p /var/www/sc/ -t /tmp

function usage ()
{
    echo -e "** param error. **"
    echo -e "usage:"
    echo -e "\tbackup --path /var/www/kilfu --to /var/www/"
    echo -e "\tbackup -p /var/www/kilfu -t /var/www/\n"
    echo -e "param:"
    echo -e "\t-p | --path\t\tfolder's path."
    echo -e "\t-t | --to\t\tthe path where compress into."
    exit
}

function check_folder_exist ()
{
    if [ -d "$1" ]; then
        return 1
    else
        echo -e "[$2] folder not found!"
        exit
    fi
}

if [ $# -le 0 ]; then
    usage
fi

while [ "$1" != "" ]; do
    case $1 in
        -p | --path )           shift
                                _path=$1
                                ;;
        -t | --to )             shift
                                _to=$1
                                ;;
        -h | --help )           usage
                                exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done

if [ $_path == "" ]; then
    $_path
fi


check_folder_exist $_path "path"
check_folder_exist $_to "to"

TODAY=`date +%Y%m%d`
IFS="/"
export IFS;
for word in $_path; do
    if [ "$word" != "" ]; then
        fname="$word"
    fi
done

cd "$_to"
echo -e "Start compressing..."
echo -e "  compress folder:\t$_path"
echo -e "  destination:\t\t$_to"

tar zcvfP "${fname}_${TODAY}.tar" "$_path"


使用方法
1:
/bin/bash backup.sh -p /var/www/sc/ -t /tmp
2: crontab
#分 時 日 月 週
# backup sc
30 3 * * * /bin/bash /var/www/sc/backup.sh --path /var/www/sc --to /home/backup/


恩,就這樣。