📦
tar cheat sheet
Think of tar's flags as a sentence: create, extract or list, then file (the archive name, which must come right after f). Add z for gzip, j for bzip2, J for xz and v for verbose.
Click any command to copy it.
Create
| Command | What it does |
|---|---|
tar -czf archive.tar.gz dir/ | Create a gzip-compressed archive of a directory. |
tar -cjf archive.tar.bz2 dir/ | Create a bzip2-compressed archive. |
tar -cJf archive.tar.xz dir/ | Create an xz-compressed archive (smaller, slower). |
tar --zstd -cf archive.tar.zst dir/ | Create a zstd-compressed archive (fast, good ratio). |
tar -cf archive.tar dir/ | Create an uncompressed archive. |
tar -czf archive.tar.gz file1 file2 dir/ | Archive several items. |
Extract
| Command | What it does |
|---|---|
tar -xf archive.tar.gz | Extract any archive; tar detects the compression. |
tar -xzf archive.tar.gz -C /target/dir | Extract into a specific directory (it must exist). |
tar -xzf archive.tar.gz path/in/archive | Extract a single file or folder. |
tar -xzf archive.tar.gz --strip-components=1 | Remove the top-level folder while extracting. |
tar -xpf archive.tar.gz | Extract preserving permissions. |
Inspect
| Command | What it does |
|---|---|
tar -tf archive.tar.gz | List the contents without extracting. |
tar -tvf archive.tar.gz | List with permissions, owner and sizes. |
tar --diff -f archive.tar -C /path | Compare the archive to files on disk. |
Excluding and streaming
| Command | What it does |
|---|---|
tar -czf a.tar.gz --exclude='*.log' --exclude='node_modules' dir/ | Skip patterns when creating. |
tar -czf a.tar.gz -T files.txt | Archive the files listed in a text file. |
tar -czf - dir/ | ssh user@host "tar -xzf - -C /dest" | Stream an archive to a remote host without a temporary file. |
tar -rf archive.tar newfile | Append a file to an uncompressed archive. |
tar -czf backup-$(date +%F).tar.gz dir/ | Name the archive with today's date. |
Frequently asked questions
Why does tar say 'Removing leading /'?
For safety tar strips the leading slash from absolute paths so extraction cannot overwrite system files. Use relative paths or -C to avoid the message.
Which compression should I choose?
gzip (z) is fastest and universal, xz (J) compresses best, and zstd (--zstd) is a good modern balance of speed and size.