Skip to content

Pack and unpack folders: tar and gzip

IntermediateLesson 20 of 667 min

Pack a folder into a .tar.gz with tar -czf, look inside with -tzf and unpack with -xzf -C, plus gzip for single files. Practise in your browser.

A folder of files is awkward to back up, download or send. tar packs it into one file, an archive, and gzip makes that file smaller. Together they make the .tar.gz files you see everywhere on Linux (also written .tgz).

The three things tar does

Pick one, then add f and the archive's name:

OptionDoesRemember it as
-ccreate an archivecreate
-tlist what's insidetable of contents
-xunpack itextract

Add -z to compress with gzip, and -v to see each file's name as it goes.

tar -czf website.tar.gz website
tar -tzf website.tar.gz

The order matters in one place: f must come last, right before the archive's name, because the name belongs to it. tar -czf backup.tar.gz website works; tar -cfz makes an archive called z.

Unpacking

tar -xzf unpacks into the folder you are in. -C picks another folder, which has to exist:

mkdir unpacked
tar -xzf website.tar.gz -C unpacked

Tip:List an archive with -t before you unpack it. Some archives hold a neat folder; others spill dozens of files straight into wherever you are.

gzip for one file

gzip notes.txt replaces the file with a smaller notes.txt.gz (-k keeps the original). gunzip turns it back, and zcat prints it without unpacking. Log files are often kept this way.

Your turn

Back up the website folder as website-backup.tar.gz in your home folder. Then look at what is inside downloads/fonts.tar.gz without unpacking it, and unpack it into a new folder called fonts.

Next