tar Cheatsheet - tar Archive & Compression Reference

Bundling a directory before a backup, a code hand-off or a server migration always goes through tar, and the difficulty is choosing a compression format and avoiding parameters that cause irreversible damage. The sheet separates creating, listing, testing and extracting, then gives formats their own comparison: gzip as a balanced default, bzip2 smaller but slower, xz best ratio with threading at a time cost, and zstd as the pragmatic modern choice. Two behaviours matter for backups: tar records ownership by default, so extraction without --no-same-owner silently changes file owners, and --exclude decides what never enters the archive — node_modules, .git and caches belong there. The riskiest moment is extraction, where an archive containing ../ entries can write outside the target directory, so list with tar -tf before unpacking. Two performance notes: parallel compression with pigz for large trees, and --strip-components to avoid an extra nesting level on extraction.

SysOps·44 commands·Last updated 2026-07-21
targzipbzip2xzCompression

Typical Use Case

For developers backing up directories, migrating servers and packaging releases. tar is not hard to remember commands for; it is hard on three counts: choosing a compression format (the speed versus ratio trade-off across gzip, zstd and xz), the trailing slash that decides whether you archive a directory or its contents, and the irreversibility of overwriting during extraction. This sheet covers packing, extraction, inspection, format comparison and advanced usage, with --exclude and --strip-components as the two parameters that save the most time and cause the most damage.

Pack & Compress 7

tar -cvf archive.tar dir/
Package into .tar (no compression): -c create, -v verbose, -f file
tar -czvf archive.tar.gz dir/
Package and gzip-compress (.tar.gz/.tgz), most common
tar -cjvf archive.tar.bz2 dir/
Package and bzip2-compress; higher ratio, slower than gzip
tar -cJvf archive.tar.xz dir/
Package and xz-compress; highest ratio, slowest
tar --zstd -cvf archive.tar.zst dir/
zstd compression; much faster than gzip, recommended on newer systems
tar -czvf archive.tar.gz --exclude="*.log" dir/
Exclude .log files while packaging
tar -czvf archive.tar.gz --exclude="node_modules" --exclude=".git" project/
Exclude multiple directories

Extract 8

tar -xvf archive.tar
Extract a .tar: -x extract
tar -xzvf archive.tar.gz
Extract .tar.gz/.tgz
tar -xjvf archive.tar.bz2
Extract .tar.bz2/.tbz2
tar -xJvf archive.tar.xz
Extract .tar.xz/.txz
tar --zstd -xvf archive.tar.zst
Extract .tar.zst
tar -xzvf archive.tar.gz -C /opt/
Extract to a target directory (-C)
tar -xzvf archive.tar.gz file.txt
Extract only a specified file from the archive
tar -xzvf archive.tar.gz --strip-components=1
Drop the top-level directory on extract

List & Test 5

tar -tf archive.tar.gz
List archive contents without extracting: -t list
tar -tzvf archive.tar.gz
List with file size and permissions
tar -tf archive.tar.gz | grep "config"
Find a specific file in the archive
gzip -t archive.tar.gz
Test gzip integrity; no output means OK
tar -dvf archive.tar
Compare archived files against those on disk

Compression Format Comparison 6

-z (gzip)
Fastest, best compatibility, .tar.gz/.tgz
-j (bzip2)
Higher ratio than gzip, slower, .tar.bz2
-J (xz)
Highest ratio, slowest, .tar.xz
--zstd (zstd)
Fast and good ratio, recommended on newer systems, .tar.zst
-a
Auto-select compression by file extension
--use-compress-program=pigz
Use pigz for multi-threaded gzip acceleration

Other Compression Tools 8

zip -r archive.zip dir/
Zip a directory
unzip archive.zip -d /opt/
Unzip to a target directory
unzip -l archive.zip
List zip contents without extracting
gzip file.txt
Compress a single file to file.txt.gz (original removed)
gzip -k file.txt
Compress while keeping the original (-k keep)
gunzip file.txt.gz
Decompress a single .gz file
zcat file.txt.gz
View .gz contents without decompressing
7z x archive.7z
Extract 7z format (requires p7zip)

Advanced Usage 6

tar -rvf archive.tar newfile.txt
Append a file to an existing .tar (not compressed)
tar -uvf archive.tar dir/
Update only files newer than those in the archive
tar -czf - dir/ | ssh host "tar -xzf - -C /dest"
Transfer and extract over an SSH pipe
tar -czf - dir/ | split -b 100M - archive.tar.gz.
Split into 100 MB volumes
cat archive.tar.gz.* | tar -xzvf -
Concatenate volumes and extract
tar -g snapshot.snar -czf backup.tar.gz dir/
Incremental backup with a snapshot file

Common Examples 4

tar -czvf backup-$(date +%F).tar.gz /home/user/
Dated directory backup
tar -czvf app.tar.gz --exclude="*.log" --exclude="tmp/" app/
Package a project excluding logs and temp files
tar -xzvf package.tar.gz --strip-components=1 -C /opt/app
Extract to a dir and drop the top level
tar -czf - /data | pigz > backup.tar.gz
Multi-threaded compress of a large dir

Parameter matrix

ParameterEffectExample
-z (gzip)速度最快、兼容性最好tar -czvf a.tar.gz dir/
--zstd速度接近 gzip、压缩率更好,新系统推荐tar --zstd -cvf a.tar.zst dir/
-J (xz)压缩率最高但最慢tar -cJvf a.tar.xz dir/
-c / -x / -t创建 / 解压 / 列出不解压tar -tf a.tar.gz
-v显示处理的文件名tar -czvf a.tar.gz dir/
--exclude打包时排除路径或模式--exclude="*.log" --exclude="node_modules/"
--strip-components=N解压时去掉前 N 层目录tar -xzf a.tar.gz --strip-components=1 -C /opt
-C dir切换到指定目录操作tar -xzf a.tar.gz -C /opt/app
-kgzip 压缩时保留原文件gzip -k file.txt
pigz多线程压缩大目录tar -czf - /data | pigz > b.tar.gz
split -b 100M分卷便于传输tar -czf - dir/ | split -b 100M - a.tar.gz.
gzip -t测试压缩包完整性,无输出即正常gzip -t a.tar.gz

Common pitfalls

Symptom解压后目录多了一层,出现 /opt/app/app/ 这样的结构。

Cause打包时源目录写法或解压时未剥离顶层目录。

Fix用 --strip-components=1 解压,或打包时用 -C dir . 让内容不带顶层目录。

Symptom打包体积巨大,node_modules 与 .git 都在里面。

Cause未使用 --exclude。

Fixtar -czvf a.tar.gz --exclude="node_modules/" --exclude=".git" --exclude="*.log" app/

Symptom解压到指定目录失败,提示权限或路径不存在。

Cause目标目录未创建。

Fix先 mkdir -p /opt/app 再配合 -C 指定。

Symptom对 .tar.gz 使用 tar -r 追加文件报错。

Cause追加只支持未压缩的 .tar 归档。

Fix需要追加内容时重新打包,或先用 gzip -d 解压再追加最后重压。

Symptom解压时报路径穿越相关警告或文件落到意外位置。

Cause归档内含 ../ 或绝对路径条目。

Fix先用 tar -tf 查看条目清单,对来路不明的包先解到隔离目录。

Symptomsplit 分卷后合并解压报损坏。

Cause漏合并某个分卷,或合并顺序不对。

Fix确认所有 .part 文件齐全后 cat a.tar.gz.* | tar -xzf - 合并解压。

Troubleshooting

  1. 1先列内容确认结构再决定怎么解

    tar -tzvf a.tar.gz | head -20

    查看条目、大小与权限;对来路不明的包尤其要先看这一步。

  2. 2解压到指定目录并剥掉顶层

    mkdir -p /opt/app && tar -xzf a.tar.gz --strip-components=1 -C /opt/app

    发布包部署的标准写法,避免双层嵌套。

  3. 3校验压缩包是否完整

    gzip -t a.tar.gz && echo OK

    无输出即正常;配合 && echo 给出明确结论便于脚本判断。

  4. 4排除无关目录后再打包

    tar -czvf app.tar.gz --exclude="*.log" --exclude="node_modules/" --exclude=".git" app/

    体积通常能降一个数量级,也避免把密钥打进包里。

  5. 5大目录用 pigz 多线程加速

    tar -czf - /data | pigz > backup.tar.gz

    多核并行压缩,通常比单线程 gzip 快数倍。

Command Examples

Package a project while excluding logs and dependencies

tar -czvf app.tar.gz --exclude="*.log" --exclude="node_modules/" --exclude=".git" app/

--exclude 在打包时过滤,比先打包再删更省时间和磁盘。多阶段构建的项目务必排除 node_modules,它通常是体积大头且可由 npm ci 重建。

Output

app/package.json
app/src/
app/src/main.ts
app/dist/
app/dist/index.js

Extract into a target directory, stripping the top folder

tar -xzvf package.tar.gz --strip-components=1 -C /opt/app

--strip-components=1 去掉包里的第一层目录,-C 指定落点。发布包部署时最常用,否则会得到 /opt/app/package/ 这样的双层结构。

Output

package.json
src/
src/main.ts
dist/index.js

Inspect an archive before extracting

tar -tzvf package.tar.gz | head -20

-t 只列表不解压,-v 显示权限与时间。确认路径结构与权限位符合预期后再解,尤其对来路不明的压缩包。

Output

-rw-r--r-- root/root     1024 2026-09-28 10:11 package.json
drwxr-xr-x root/root      4096 2026-09-28 10:11 src/
-rwxr-xr-x root/root    24576 2026-09-28 10:12 dist/index.js

Package while preserving timestamps

tar -czvf backup-$(date +%F).tar.gz /home/user/ gzip -t backup-$(date +%F).tar.gz && echo OK

gzip -t 测完整性,无输出即正常;这里用 && echo OK 把它变成一条明确的结论。用日期命名避免多次备份互相覆盖。

Output

OK

Common Pitfalls

  • tar -x overwrites same-named files without prompting, and paths containing .. or absolute paths can write outside the target — inspect with -t before extracting anything untrusted.
  • Without --exclude, tar -c bundles node_modules and .git too, which can multiply the size and leak secrets.
  • The flag after -f must match the compression actually used; mismatching -j with a .gz file silently produces the wrong format.
  • Appending with tar -r only works on uncompressed .tar — using it on .tar.gz errors out or corrupts the archive.
  • After split, every volume must be concatenated with cat archive.* before extracting, or you get a truncated archive.

Tips

  • Mnemonic: c=create, x=extract, t=list, z=gzip, j=bzip2, J=xz.
  • Before extracting, run tar -tf to inspect contents and confirm there's no ../ path traversal (zip-slip risk).
  • For large files, zstd --long=31 uses long-distance matching — 5-10x faster than gzip with better ratio.
  • Appending works only on uncompressed .tar; for .tar.gz you must decompress and repackage.
  • pigz is the multi-threaded gzip; for large files use tar -cf - dir | pigz > out.tar.gz to speed up greatly.
  • Put -C (target dir) after the filename; --strip-components drops the first N directory levels to avoid nested extraction.

FAQ

Which compression format should I use — gzip, bzip2, xz or zstd?

It comes down to speed versus ratio. gzip is fastest with the widest compatibility and is fine for everyday archiving; zstd is close to gzip in speed with a noticeably better ratio and is the better default on modern systems; xz compresses hardest but is slowest, which suits files you archive and rarely reopen; bzip2 is largely obsolete now. The flags are -z, --zstd and -J respectively.

How do I exclude node_modules and logs when creating a tarball?

Use --exclude, for example tar -czvf app.tar.gz --exclude="*.log" --exclude="node_modules/" --exclude="tmp/" app/. Better still, think of it like .gitignore or .dockerignore — clean up before packing, since these files dominate the size and can always be regenerated. Also prefer -C to change directory so the archive does not gain an extra nesting level.

How do I extract without the top-level directory?

Add --strip-components=1: tar -xzvf package.tar.gz --strip-components=1 -C /opt/app. The archive entry app/package.json then lands at /opt/app/package.json instead of /opt/app/app/package.json. This is the standard trick for release tarballs and deploy scripts, usually paired with -C to pick the destination.

How can I inspect an archive without extracting it?

Use -t to list rather than extract: tar -tzvf archive.tar.gz prints names, sizes and permissions without unpacking. Pipe it to search: tar -tf archive.tar.gz | grep "config". And gzip -t archive.tar.gz quickly tests integrity — no output means the archive is fine.

Packing a large directory is slow — how do I speed it up?

Compression is the bottleneck, so use pigz for multi-threaded compression: tar -czf - /data | pigz > backup.tar.gz. It parallelizes across cores and is typically several times faster than single-threaded gzip. If a single file is too big, split it with tar -czf - dir/ | split -b 100M - archive.tar.gz. and reassemble later with cat archive.tar.gz.* | tar -xzvf -.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us