首页·终端命令

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