Archive versus compress
tar collects multiple paths into one archive; it does not necessarily compress them. The -z flag pipes through gzip, so tar -czf backup.tar.gz project/ both archives and compresses. For extraction, replace -c with -x: tar -xzf backup.tar.gz.
| tar flag | Meaning |
|---|---|
-c |
create archive |
-x |
extract archive |
-t |
list contents without extracting |
-z |
gzip compression |
-j |
bzip2 compression |
-J |
xz compression |
-f |
next argument is the archive name |
-v |
print names; optional |
-C dir |
extract into another directory |
Always run tar -tzf backup.tar.gz before extracting an archive you did not create, so you can see whether it unpacks into its own folder or scatters files into the current one. --exclude='*.log' leaves matching files out when creating an archive.
flowchart LR D["Many files<br/>project/"] -- "tar -cf" --> T["project.tar<br/>one archive"] T -- "gzip / xz" --> C["project.tar.gz<br/>smaller"] C -- "tar -tzf" --> L["List contents<br/>check first"] L -- "tar -xzf -C /tmp" --> X["Extracted<br/>in a safe place"] %% step D: You start with a directory of many files. %% step T: tar collects them into one file, keeping paths and permissions. No size change yet. %% step C: A compressor makes it smaller; tar -czf does both steps at once. %% step L: List the archive before extracting so you know what it will create. %% step X: Extract into a chosen directory with -C so nothing is overwritten by surprise.
Single-file compressors
gzip big.log compresses one file into big.log.gz and replaces the original by default; gzip -k keeps the original. gunzip reverses the operation. Gzip does not accept a directory directly, so archive a directory tree with tar first.
zcat, zless, and zgrep read .gz files without unpacking them, which is how rotated logs such as syslog.2.gz are usually inspected.
Choosing a format
| Format | Trade-off |
|---|---|
gzip (.gz) |
Fast and available everywhere |
bzip2 (.bz2) |
Smaller output, slower |
xz (.xz) |
Smallest output, slowest to create |
zip |
One file holds many entries; common when sharing with Windows users |
zip -r site.zip site/ and unzip site.zip work on whole directories without tar. Already-compressed data such as JPEG images or video barely shrinks, so compressing it again mostly wastes CPU.
Check before and after
du -sh project/ estimates space before or after archiving; do not treat its output as a guaranteed compressed size. After copying an archive to another machine, compare sha256sum backup.tar.gz on both sides to confirm it arrived intact.