Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 終端機一次解壓多個 tarball / zip 檔案的正確姿勢

編輯:關於 Linux

嘗試 tar xf *.tar 卻收到 Not found in archive 錯誤?這是因為 Shell 先將 *.tar 展開為多個檔名,導致 tar 誤以為第一個檔是壓縮包、其餘是要解壓的成員。正解是使用 for 迴圈逐個處理,或善用 unzip 的模式匹配功能。

tar 解壓多檔錯誤示例

錯誤示範與原因

$ ls
backup1.tar backup2.tar backup3.tar
$ tar xf *.tar
tar: backup2.tar: Not found in archive
tar: backup3.tar: Not found in archive
tar: Exiting with failure status due to previous errors

Shell 實際執行:tar xf backup1.tar backup2.tar backup3.tar
tar 視 backup1.tar 為壓縮包,試圖從中解壓 backup2.tar、backup3.tar —— 當然找不到。

正解一:for 迴圈逐個解壓(通用於 tar、zip、gz 等)

# 解壓所有 .tar
for f in *.tar; do
    tar xf "$f"
done

# 解壓所有 .zip
for f in *.zip; do
    unzip "$f"
done

# 解壓所有 .tar.gz
for f in *.tar.gz; do
    tar xzf "$f"
done

要點:
1. 變數 $f 必須加雙引號,防檔名含空格拆分。
2. 迴圈在當前 Shell 執行,無子行程開銷。

正解二:unzip 內建模式匹配(僅限 zip)

unzip "*.zip"    # 雙引號防 Shell 展開,交由 unzip 內部解析
# 或
unzip \*.zip     # 反斜線跳脫,同樣效果

unzip 會自行遍歷當前目錄匹配 *.zip 的所有檔案並依序解壓,無需外層迴圈。

進階:遞迴解壓子目錄下所有壓縮檔

find . -name '*.tar' -exec tar xf {} \;
find . -name '*.zip' -exec unzip {} \;

或搭配 parallel 並行加速:
find . -name '*.tar' | parallel tar xf {}

小結

工具單檔指令多檔正解遞迴解壓
tartar xf a.tarfor f in *.tar; do tar xf "$f"; donefind . -name '*.tar' -exec tar xf {} \;
unzipunzip a.zipunzip "*.zip" 或 for f in *.zip; do unzip "$f"; donefind . -name '*.zip' -exec unzip {} \;
gzipgzip -d a.gzfor f in *.gz; do gzip -d "$f"; donefind . -name '*.gz' -exec gzip -d {} \;

記住核心原則:**讓單一壓縮工具一次只處理一個壓縮包**,即可避開所有「多檔解壓」陷阱。

Copyright © Windows教程網 All Rights Reserved