Skip to content
Intermediate LinuxLesson 11 of 27 2 min read

Archives and Compression

Bundle files with tar, and shrink them with gzip.

On this page5 sections

Two separate ideas get bundled together so often that people mix them up: archiving (combining many files into one) and compression (shrinking the size of a file). tar does the first, gzip does the second, and together they produce the .tar.gz files you have almost certainly downloaded before.

tar: packing many files into one

The name is short for "tape archive" - it dates back to literal magnetic tape backups, which is why the flags feel a bit old-fashioned. Three flags cover most of what you need:

bash
tar -cf site.tar site/        # create an archive from the site/ directory
tar -tf site.tar               # list what's inside, without extracting
tar -xf site.tar               # extract into the current directory

Read the letters as: create, extract, table-of-contents, and file (always followed by the archive's name).

Adding compression

tar bundles files but does not shrink them by itself. Add -z to also gzip-compress the result, which is where the familiar .tar.gz (or .tgz) extension comes from:

bash
tar -czf site.tar.gz site/     # create AND compress in one step
tar -xzf site.tar.gz            # decompress AND extract in one step

gzip and gunzip on their own

You do not need tar to compress a single file:

bash
gzip access.log          # replaces access.log with access.log.gz
gunzip access.log.gz     # reverses it, restoring access.log
gzip -k access.log       # -k keeps the original instead of replacing it

Try it

Run these in the practice terminal (opens in a new tab). It opens in a new tab, so you keep your place here.
bash
mkdir -p site/css
echo "<h1>hi</h1>" > site/index.html
echo "body { color: navy; }" > site/css/style.css
tar -czf site.tar.gz site
tar -tzf site.tar.gz
rm -r site
tar -xzf site.tar.gz
cat site/index.html

Everything comes back exactly as it was, even though site/ itself was deleted in between.

Further reading

  • "The Linux Command Line" by William Shotts (No Starch Press) - its chapter on archiving and backup covers tar, gzip, and their relatives (bzip2, xz, zip) side by side, including when to reach for each one.
  • "How Linux Works" by Brian Ward (No Starch Press) - explains what compression is actually doing to the bytes, which demystifies why some file types (already-compressed video or images) barely shrink at all.

Challenge

Bundle the site directory into a single archive called site.tar using tar.

Want to experiment first? Try things in the practice terminal (opens in a new tab), then enter the command that solves the task here.

Quiz

Lock in the concepts. Score at least 80% to mark the lesson complete.

0 of 2 answered

Done with this one?

Skipped the challenge? You can mark the lesson complete by hand.

Your notes

Kept on this browser only.