Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Linux 自動備份腳本(第二版):以時間戳偵測變動檔案

這一版備份腳本相較於上一版,新增了「記錄時間戳」的功能,可以即時偵測並備份你修改過的檔案,特別適合個人照片、文件與程式碼的備份。

使用方式

在 ./backup_file 目錄下應有一個 list_file 子目錄,用來存放檔案清單與時間戳。執行時傳入兩個參數:$1 為要備份的來源目錄(不可為空),$2 為備份目標目錄。

目前這版仍有局限:只能備份檔案,尚無法處理子目錄,後續版本會補上這個功能。若你發現某段程式碼有 Bug,或有更好的實作方式,歡迎一起討論。

腳本內容

#!/bin/sh
# name: backup file
# author: acanoe
# version: 0.1

judge_your_input() {
    if [ -z $1 ]; then
        echo "please input your updatedir!"
        echo "example: ./back_file /backdir /updatedir"
        exit
    fi
    if [ -z $2 ]; then
        echo "please input your backdir!"
        echo "example: ./back_file /backdir /updatedir"
        exit
    fi
}

clear_record() {
    if [ -e ./list_file/old_time_ioc ]; then
        rm ./list_file/old_time_ioc
    fi
    if [ ! -e ./list_file/new_time_ioc ]; then
        touch ./list_file/new_time_ioc
    fi
    if [ -e ./list_file/new_time_ioc ]; then
        mv ./list_file/new_time_ioc ./list_file/old_time_ioc
    else
        touch ./list_file/old_time_ioc
    fi
}

find_change_file() {
    ls $1 > ./list_file/update_file_list
    ls $2 > ./list_file/back_file_list
    while read line; do
        R=$(echo $line)
        echo "$R `stat $1/$R | sed -n '7p'`" >> ./list_file/new_time_ioc
    done < ./list_file/update_file_list

    diff ./list_file/new_time_ioc ./list_file/old_time_ioc > ./list_file/diff_file
    sed -n '/</p' ./list_file/diff_file > ./list_file/file
    sed -e 's/< //g' ./list_file/file > ./list_file/the_file
}

back_back_file() {
    while read line; do
        R=$(echo $line | sed -e 's/ .*//g')
        echo $R
        cp $1/$R $2
    done < ./list_file/the_file
}

find_not_exist() {
    ls $1 > ./list_file/file_list
    ls $2 > ./list_file/back_list
    diff ./list_file/file_list ./list_file/back_list > ./list_file/diff_file
    sed -n '/</p' ./list_file/diff_file > ./list_file/file
    sed -e 's/< //g' ./list_file/file > ./list_file/the_file
    while read line; do
        R=$(echo $line)
        echo $R
        cp -rf $1/$R $2
    done < ./list_file/the_file
}

judge_your_input $1 $2
clear_record
find_change_file $1 $2
back_back_file $1 $2
find_not_exist $1 $2
Copyright © Linux教程網 All Rights Reserved