首頁·終端機命令

tar

壓縮與傳輸

用法

tar -czf <archive.tar.gz> <path>

它只把檔案打成一個包,本身並不壓縮——壓縮是 `-z`(gzip)、`-j`(bzip2)、`-J`(xz)的事;建立 `-c`、解壓 `-x`、查看 `-t` 三種模式只能選一個且要寫在前面,而經典寫法裡 `-f` 必須是最後一個選項,包名緊跟其後。

常用選項

選項含義
-c / -x / -tCreate / extract / list. Exactly one of the three, and it comes first.
-f <file>The archive name, and it must be the last flag before that name.
-z / -j / -Jgzip / bzip2 / xz. GNU tar detects the format when extracting, so -z is optional with -x.
-vPrint the file names as they go past.
-C <dir>Change into that directory first. Position in the command line matters.
--exclude='node_modules'Skip matching paths. Write it before the source paths.
--strip-components=1Drop the top-level directory when extracting.
--zstdUse zstd instead of gzip (GNU tar 1.31 and newer).

範例

tar -czf site.tar.gz -C /var/www .

Archive the contents of a directory without the leading path.

tar -xzf site.tar.gz -C /tmp/restore

Extract into a directory that already exists.

tar -tzf site.tar.gz | head

Look inside before extracting, so nothing lands in $PWD by surprise.

打包和壓縮是兩件事:tar 打包,gzip 壓小,.tar.gz 是兩樣一起。

怎麼看

  • 方括號 [ ] 表示這部分可以不寫。
  • 省略號 … 表示可以寫多個。
  • 選項區分大小寫——有些命令裡 -r 和 -R 不是一回事。

常見問題

Q. tar 是做什麼的?

它只把檔案打成一個包,本身並不壓縮——壓縮是 `-z`(gzip)、`-j`(bzip2)、`-J`(xz)的事;建立 `-c`、解壓 `-x`、查看 `-t` 三種模式只能選一個且要寫在前面,而經典寫法裡 `-f` 必須是最後一個選項,包名緊跟其後。

Q. 怎麼寫?

tar -czf <archive.tar.gz> <path> —— 方括號表示可以省略的部分。

Q. 值得記的選項有幾個?

這裡列了 8 個,完整列表在 man tar。這條命令屬於壓縮與傳輸。

相關命令

man 手冊: man tar