天天看點

linux下tar壓縮/解壓的使用(tar) 壓縮/解壓

壓縮:

tar -zcvf 壓縮後檔案名.tar.gz 被壓縮檔案

解壓:

tar -zxvf 被解壓檔案

注意:不要有多餘的空格,一個空格即可。

具體的可以在linux環境下 用 tar --help 檢視詳細說明

格式:tar [option] file

           -c  create  create a new archive

           -x  extract extract files from an archive

           -t  list       list the contents of an archive

            其中c/x/t不能同時存在

           -z   --gzip, --gunzip, --ungzip   filter the archive through gzip

           -j,  --bzip2                filter the archive through bzip2

           -f,  --file=ARCHIVE         use archive file or device ARCHIVE

           -v,  --verbose              verbosely list files processed

-p :使用原檔案的原來屬性(屬性不會依據使用者而變)

-P :可以使用絕對路徑來壓縮!

-N :比後面接的日期(yyyy/mm/dd)還要新的才會被打包進建立的檔案中!

--exclude FILE:在壓縮的過程中,不要将 FILE 打包!

範例:

tar -cvf /tmp/etc.tar  *.jpg  将所有jpg檔案打包

範例一:将整個 /etc 目錄下的檔案全部打包成為 /tmp/etc.tar

[root@linux ~]# tar -cvf /tmp/etc.tar /etc      <==僅打包,不壓縮!

[root@linux ~]# tar -zcvf /tmp/etc.tar.gz /etc     <==打包後,以 gzip 壓縮

[root@linux ~]# tar -jcvf /tmp/etc.tar.bz2 /etc    <==打包後,以 bzip2 壓縮

# 特别注意,在參數 f 之後的檔案檔名是自己取的,我們習慣上都用 .tar 來作為辨識。

# 如果加 z 參數,則以 .tar.gz 或 .tgz 來代表 gzip 壓縮過的 tar file ~

# 如果加 j 參數,則以 .tar.bz2 來作為附檔名啊~

# 上述指令在執行的時候,會顯示一個警告訊息:

# 『tar: Removing leading `/" from member names』那是關于絕對路徑的特殊設定。

範例二:查閱上述 /tmp/etc.tar.gz 檔案内有哪些檔案?

[root@linux ~]# tar -ztvf /tmp/etc.tar.gz

# 使用了 gzip 壓縮,是以要查閱該 tar file 内的檔案時,

# 就要加上 z 這個參數

範例三:将 /tmp/etc.tar.gz 檔案解壓縮在 /usr/local/src 底下

[root@linux ~]# cd /usr/local/src

[root@linux src]# tar  -zxvf  /tmp/etc.tar.gz

# 在預設的情況下,可以将壓縮檔在任何地方解開

# 先将工作目錄變換到 /usr/local/src 底下,并且解開 /tmp/etc.tar.gz ,

# 則解開的目錄會在 /usr/local/src/etc !另外,如果進入 /usr/local/src/etc

# 則會發現,該目錄下的檔案屬性與 /etc/ 可能會有所不同!

範例四:在 /tmp 底下,隻想要将 /tmp/etc.tar.gz 内的 etc/passwd 解開而已

[root@linux ~]# cd /tmp

[root@linux tmp]# tar -zxvf /tmp/etc.tar.gz etc/passwd

# 可以用 tar -ztvf 來查閱 tarfile 内的檔案名稱,如果單隻要一個檔案,

# 就可以通過這個方式來下達!注意到! etc.tar.gz 内的根目錄 / 是被拿掉了!

範例五:将 /etc/ 内的所有檔案備份下來,并且儲存其權限!

[root@linux ~]# tar -zxvpf /tmp/etc.tar.gz /etc

# 這個 -p 的屬性是很重要的,尤其是當您要保留原本檔案的屬性時!

範例六:在 /home 當中,比 2005/06/01 新的檔案才備份

[root@linux ~]# tar -N "2005/06/01" -zcvf home.tar.gz /home

範例七:要備份 /home, /etc ,但不要 /home/dmtsai

[root@linux ~]# tar --exclude /home/dmtsai -zcvf myfile.tar.gz /home/* /etc

範例八:将 /etc/ 打包後直接解開在 /tmp 底下,而不産生檔案!

[root@linux tmp]# tar -cvf - /etc | tar -xvf -

# 這個動作有點像是 cp -r /etc /tmp  依舊是有其有用途的!

# 要注意的地方 輸出檔變成 - 而輸入檔也變成 - ,又有一個 | 存在~

# 這分别代表 standard output, standard input 與管線指令!

繼續閱讀