Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

tar 指令詳解與全量/增量備份實作

先把三個名詞分清楚:全量備份是對所有檔案做一次完整備份;增量備份只備份本次與上一次備份之間的差異;差異備份則是以全量为基礎,備份其後每一次的變化。

建立測試資料

mkdir -p /work/upload
cd /work/upload/
touch aa0{1,2,3,4,5}.txt

基本打包與解包

# 打包(-c 建立、-v 顯示過程、-f 指定檔案)
tar -cvf upload01.tar /work/upload/
tar: Removing leading `/' from member names

# 檢視內容
tar -tf upload01.tar

# 解包到指定位置(-C 切換目錄)
rm -rf /work
tar -xvf upload01.tar -C /

預設 tar 會把絕對路徑開頭的 / 拿掉,這是安全設計,避免解開時直接覆蓋系統檔案。若想保留完整路徑,加 -P:

tar -cPvf upload02.tar /work/upload/
tar -xPvf upload02.tar        # 解開時不必再指定 -C

不見得要 -f:用重定向也行

tar -cv /work/upload/ > upload03.tar
tar -xv -C / < upload03.tar
tar -tf upload03.tar

若寫成 tar -cv upload03.tar /work/upload/ 而漏掉 -f,tar 會把 upload03.tar 當成要打包的來源,結果把打包資料混進輸出,錯誤訊息是 Cannot stat: No such file or directory。

路徑寫法會影響解壓位置

cd /work
tar -cf upload04.tar upload/     # 記錄的是相對路徑 upload/
tar -xv -C / < upload04.tar      # 解開後出現在 /upload/

可見打包時記錄的路徑形式,直接決定還原後檔案落在哪裡。

追加與更新

touch /work/upload/aa06.txt
tar -Pvf upload02.tar -r /work/upload/aa06.txt    # -r 追加

vim /work/upload/aa01.txt
tar -uPvf upload02.tar /work/upload/            # -u 更新已變動的檔案

搭配 find 與清單檔

# 打包 /etc 下所有 .conf
find /etc/ -name "*.conf" | xargs tar -Pcvf test01.tar

# 排除 yum.conf
find /etc/ -name "*.conf" ! -name "yum.conf" | xargs tar -Pcvf test02.tar

# 用清單檔 -T 指定來源
find /etc -name "*.conf" > file1
tar -cPvf conf01.tar -T file1
ls -lh conf01.tar

用 -g 實現增量備份

關鍵參數是 -g,它會維護一個「標誌檔」記錄上次備份的狀態:

# 第一次:全量
tar -g flag -cPvf upload01.tar /work/upload/
tar: /work/upload: Directory is new

# 新增 aa07.txt、修改 aa02.txt 之後
tar -g flag -cPvf upload02.tar /work/upload/
tar -tPf upload02.tar
# 只列出 /work/upload/、aa02.txt、aa07.txt

# 再新增 aa08.txt、刪除 aa01.txt
tar -g flag -cPvf upload03.tar /work/upload/

還原順序:全量而後逐個增量

rm -rf /work/*
tar -g flag -xPvf upload01.tar      # 先還全量
tar -g flag -xPvf upload02.tar      # 再疊加第一次增量
tar -g flag -xPvf upload03.tar
tar: Deleting `/work/upload/aa01.txt'   # 增量會同步處理刪除
ls /work/upload/

要留意的是,還原全量之後立刻看 aa02.txt 會發現內容是舊的,必須把後續增量依序疊上去才完整;而 -g 的標誌檔必須全程保留,一旦遺失就無法正確銜接。此外,增量鏈越長、還原步驟越多,因此實務上通常定期做一次新的全量來截斷鏈條。

Copyright © Linux教程網 All Rights Reserved