Skip to content

Linux Foundations / Manage a Linux host ยท Step 17 of 50

Lesson: tar and gzipSwitch
โ† Linux Foundations

System administration

tar and gzip

Bundle many files into one archive with tar and shrink it with gzip.

Linux separates two jobs that other systems often combine. Archiving puts many files into one file. Compression makes a file smaller. tar does the first, gzip does the second.

gzip

gzip compresses a single file:

$ ls
notes.txt
$ gzip notes.txt
$ ls
notes.txt.gz

Note that the original file is replaced. To restore it, run gunzip notes.txt.gz (or gzip -d notes.txt.gz). Use -k to keep the input file. Very old versions of gzip lack -k.

Creating a tar archive

$ tar -cvf project.tar project/
project/
project/main.c
project/README
  • -c creates an archive
  • -v lists files as it works
  • -f project.tar names the archive file

The name must follow -f directly. A plain .tar file is not compressed.

Listing and extracting

Look inside before you extract:

$ tar -tf project.tar
project/
project/main.c
project/README

Then unpack with -x:

$ tar -xf project.tar

Files land in the current directory and can overwrite files with the same names. Use -C to extract somewhere else. The directory must already exist:

$ mkdir restore
$ tar -xf project.tar -C restore

tar with compression

tar can run the compressor for you. Add -z for gzip:

$ tar -czf project.tar.gz project/
$ tar -xzf project.tar.gz

-j selects bzip2 (.tar.bz2) and -J selects xz (.tar.xz). These need the matching compression program installed. GNU tar, the usual version on Linux, detects the compression when reading from a file, so tar -xf project.tar.gz also works.

The short name .tgz means the same as .tar.gz.

Compression pays off on text such as source code and logs. Files that are already compressed, such as JPEG photos or most video, barely shrink.

Try it

$ mkdir demo
$ echo "hello" > demo/a.txt
$ tar -czf demo.tar.gz demo
$ tar -tzf demo.tar.gz
demo/
demo/a.txt
$ mkdir out
$ tar -xzf demo.tar.gz -C out
$ cat out/demo/a.txt
hello

For more practice, open the search and archives lab.

Check your understanding

tar and gzip

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.