Archiving and Compressing — tar and gzip
At the end of the season, Asha wants to back up the whole garden folder as one small file she can email or copy to another machine. Two separate jobs are involved: bundling many files into one, and squeezing that one file so it takes less space. Linux has a tool for each, and one command that does both.
The rule
tar bundles, gzip squeezes; tar -czf does both.
tar packs files and folders into a single archive and keeps their names, folders and permissions. On its own it doesn't make anything smaller. gzip compresses a single file.
$ gzip notes.txt # replaces notes.txt with notes.txt.gz
$ gunzip notes.txt.gz # turns it back into notes.txtTogether, from Asha's home directory:
$ tar -czf garden.tar.gz garden/ # create, gzip, into this file
$ tar -tzf garden.tar.gz # list what's inside
$ tar -xzf garden.tar.gz # extract here
$ tar -xzf garden.tar.gz -C /tmp/restore # extract into another folderEach letter is a small instruction:
| Letter | Means |
|---|---|
c |
create an archive |
x |
extract from one |
t |
list the contents ("table") |
z |
use gzip (.tar.gz or .tgz) |
j |
use bzip2 (.tar.bz2) |
J |
use xz (.tar.xz), smaller but slower |
v |
verbose: print each file name |
f |
the next word is the archive's file name |
When extracting, GNU tar can detect the compression type on its own, so tar -xf garden.tar.gz also works.
You'll also meet zip files, especially ones shared with Windows users. zip -r garden.zip garden/ bundles and compresses in one step, and unzip garden.zip unpacks it.
The shortcut
Build a tar command as one action letter, one squeeze letter, then f last: action (c, x or t) + compression (z, j or J) + f, followed straight away by the archive's name. The order of the other letters doesn't matter, but f must be right before the file name.
Action
She's making an archive, so the action is
c.
The trap is putting f in the middle, as in tar -cfz garden.tar.gz garden/. Now z is taken as the archive's name, so tar writes an uncompressed archive called z. Keep f last among the letters.
Drills
Answer fast — trust the rule.
Which command creates a gzip-compressed archive of the garden folder?
How do you see what's inside garden.tar.gz without extracting it?
What does gzip notes.txt leave in the folder?
Asha types tar -cfz backup.tar.gz garden/. What goes wrong?
Remember
- tar bundles, gzip squeezes, and
tar -czfdoes both. - Build it as an action letter, a squeeze letter, then
flast, followed by the archive name. - Check an archive with
-tbefore relying on it, and extract into a separate folder with-C.
