How to Extract a tar.gz File in Linux

Unpack tar.gz, tar.bz2, tar.xz and zip archives from the command line.

A .tar.gz is two things stacked: tar bundles files into one stream, gzip compresses that stream. Extracting undoes both at once. Modern versions of tar detect the compression automatically, so tar -xf works for .gz, .bz2 and .xz alike — but the explicit flags still appear everywhere, so it pays to know what they mean.

Step by step

1 Look inside before extracting

$ tar -tzf archive.tar.gz | head

Lists the contents without unpacking anything. Do this with archives from the internet: a well-behaved one contains a single top-level directory, while a "tar bomb" sprays hundreds of files into your current directory.

2 Extract it

$ tar -xzf archive.tar.gz

Unpacks into the current directory. Add -v to watch the files as they come out.

3 Extract somewhere specific

$ tar -xzf archive.tar.gz -C /opt/app

The -C changes directory before extracting. The target must already exist — create it with mkdir -p first.

4 Other compression formats

$ tar -xjf file.tar.bz2    # bzip2
tar -xJf file.tar.xz     # xz
unzip file.zip           # zip

Or simply tar -xf for any of the tar variants: modern tar recognises the format by itself. Only creating an archive requires you to choose.

5 Extract a single file

$ tar -xzf archive.tar.gz path/inside/file.txt

Give the exact path as shown by tar -tzf. Useful for pulling one config out of a large backup.

Tips worth knowing

Frequently asked questions

What does tar -xzf mean?

x = extract, z = decompress with gzip, f = the archive filename follows. Together: extract this gzipped archive.

Can I extract without knowing the compression?

Yes. tar -xf archive.tar.anything works on modern systems — tar inspects the file and picks the right decompressor.

How do I extract into a folder that does not exist?

mkdir -p target && tar -xzf archive.tar.gz -C target. The -C flag does not create the directory for you.

What is a tar bomb?

An archive with no top-level directory, which scatters its contents into your current folder. Checking with tar -tzf first is the cheap defence.

The commands behind it

tar

Create and extract archives: tar.gz, tar.bz2 — with the flag combinations finally explained.

gzip & zip

Single-file compression (gzip family) vs portable archives (zip) — and when each.

ls

List the contents of a directory, with options for hidden files, long format, sorting and more.

Choosing between tools

tar.gz vs zip

tar.gz compresses better and preserves Unix permissions; zip opens with a double click on any system.

More how-to guides

Check disk space in Linux

See how much space is left, and find out what is using it.

Free a port that is already in use

Find which process holds a port and stop it cleanly.

Find and replace text in files

Replace text in one file or across a whole project, safely.

Make a script executable

Give a script permission to run, and understand why it needs it.