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

$ 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 {}
| 工具 | 單檔指令 | 多檔正解 | 遞迴解壓 |
|---|---|---|---|
tar | tar xf a.tar | for f in *.tar; do tar xf "$f"; done | find . -name '*.tar' -exec tar xf {} \; |
unzip | unzip a.zip | unzip "*.zip" 或 for f in *.zip; do unzip "$f"; done | find . -name '*.zip' -exec unzip {} \; |
gzip | gzip -d a.gz | for f in *.gz; do gzip -d "$f"; done | find . -name '*.gz' -exec gzip -d {} \; |
記住核心原則:**讓單一壓縮工具一次只處理一個壓縮包**,即可避開所有「多檔解壓」陷阱。