萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 壓縮解壓縮指令大全:tar、gzip、bzip2、xz、zip、7z、rar 參數與實戰對照表

壓縮格式與工具對照

副檔名工具解壓縮指令壓縮指令特色
.tartartar xvf file.tartar cvf file.tar dir/僅打包,不壓縮
.gzgzipgunzip file.gz / gzip -d file.gzgzip file速度快、相容性佳
.tar.gz / .tgztar+gziptar zxvf file.tar.gztar zcvf file.tar.gz dir/最常見 Linux 發布格式
.bz2bzip2bunzip2 file.bz2 / bzip2 -d file.bz2bzip2 file壓縮率較 gzip 高、速度較慢
.tar.bz2tar+bzip2tar jxvf file.tar.bz2tar jcvf file.tar.bz2 dir/原始碼釋出常用
.xzxzxz -d file.xz / unxz file.xzxz -z file壓縮率最高、核心/大型專案常用
.tar.xztar+xztar Jxvf file.tar.xztar Jcvf file.tar.xz dir/Linux 核心、systemd 釋出格式
.zipzip/unzipunzip file.zipzip -r file.zip dir/跨平台相容、Windows 內建支援
.7z7z/7za7z x file.7z7z a file.7z dir/壓縮率極高、支援 AES-256 加密
.rarrar/unrarunrar x file.rarrar a file.rar dir/專有格式,Linux 需安裝非自由套件

tar 關鍵參數速記

  • c:建立
  • x:解開
  • v:顯示過程
  • f:指定檔案(必須在最後)
  • z:gzip
  • j:bzip2
  • J:xz
  • p:保留權限
  • C:切換目錄 tar xvf file.tar -C /target
  • --exclude:排除 tar czvf backup.tar.gz --exclude='*.log' /var/www

實戰範例

打包並壓縮目錄

# gzip(快、通用)
tar czvf project.tar.gz project/

# xz(最高壓縮率、較慢)
tar cJvf project.tar.xz project/

# 多核心並行壓縮(需安裝 pigz/pixz)
tar --use-compress-program=pigz -cvf project.tar.gz project/
tar --use-compress-program=pixz -cvf project.tar.xz project/

解壓縮到指定目錄

tar xvf project.tar.gz -C /opt/
unzip project.zip -d /opt/
7z x project.7z -o/opt/

僅查看壓縮包內容

tar tvf project.tar.gz
unzip -l project.zip
7z l project.7z

解壓縮單一檔案

tar xvf project.tar.gz path/to/file.txt
unzip project.zip path/to/file.txt -d /tmp/
7z x project.7z path/to/file.txt -o/tmp/

分割大檔案

# 分割成 100MB 一片
tar czvf - project/ | split -b 100M - project.tar.gz.
# 合併還原
cat project.tar.gz.* | tar xzvf -

常見問題

  • tar: Cannot open: No such file or directory → -f 參數後須緊接檔名,不可插入其他參數
  • gzip: stdin: not in gzip format → 檔案非 gzip 格式,嘗試 file 指令辨識
  • 權限錯誤 → 加 sudo 或確認目錄寫入權限
  • 解壓縮後檔名亂碼(zip 跨平台編碼) → unzip -O cp950 file.zip 指定編碼

一鍵解壓縮腳本

#!/bin/bash
# extract.sh - 智慧解壓縮
for f; do
  case "$f" in
    *.tar.gz|*.tgz) tar xzvf "$f" ;;
    *.tar.bz2)      tar xjvf "$f" ;;
    *.tar.xz)       tar xJvf "$f" ;;
    *.tar)          tar xvf "$f" ;;
    *.gz)           gunzip "$f" ;;
    *.bz2)          bunzip2 "$f" ;;
    *.xz)           unxz "$f" ;;
    *.zip)          unzip "$f" ;;
    *.7z)           7z x "$f" ;;
    *.rar)          unrar x "$f" ;;
    *) echo "Unknown format: $f" ;;
  esac
done

使用:chmod +x extract.sh && ./extract.sh *.tar.gz *.zip

copyright © 萬盛學電腦網 all rights reserved