↑↓ move Enter open Esc close

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

Choosing between tools

More how-to guides