HOWTO · Linux

How to Unzip .gz File in Linux

Learn how to decompress a .gz file or extract a .tar.gz archive on Linux with gunzip, gzip -d, and tar, and choose whether to keep the compressed original.

On this page

To decompress a standalone .gz file on Linux, use gunzip filename.gz or gzip -d filename.gz. To unpack a .tar.gz archive, use tar -xzf filename.tar.gz. By default, decompression removes the compressed input; add -k when you want to keep it.

Understanding .gz and .tar.gz Files

A .gz file is one file compressed with gzip; the extension does not mean it contains a collection of files. A .tar.gz file is a tar archive that has then been compressed with gzip, so it can hold multiple files and directories. Use gunzip or gzip -d for a standalone .gz file, and tar to extract a .tar.gz archive.

Decompressing a .gz File with gunzip

Run gunzip report.txt.gz to decompress the file in its current directory. After successful decompression, the result is report.txt, and report.txt.gz is removed. To retain the compressed copy, add -k, as in gunzip -k report.txt.gz.

This self-contained example creates a sample file, compresses it, decompresses it while keeping the compressed copy, and prints the restored contents:

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
cd "$tmpdir"
printf 'Linux notes\n' > notes
gzip notes
gunzip -k notes.gz
cat notes
Linux notes

Decompressing a .gz File with gzip -d

The -d option tells gzip to decompress, so gzip -d report.txt.gz performs the same basic task as gunzip report.txt.gz. It writes report.txt beside the input and normally removes report.txt.gz after successful decompression. Use gzip -dk report.txt.gz to keep both files. Choose either command based on which name is easier to remember; both handle a single gzip-compressed file.

Extracting a .tar.gz Archive with tar

Use tar -xzf project.tar.gz to extract an archive compressed with gzip. The options mean: -x extracts, -z handles gzip compression, and -f names the archive file. By default, tar writes the archived paths under the current working directory, so run the command from the directory where you want those paths created. To choose another destination, add -C /path/to/destination, for example tar -xzf project.tar.gz -C /tmp/project.

A .tar.gz archive and a standalone .gz file need different commands: tar reads the archive layer and restores its member files, while gunzip decompresses one gzip stream into a file. The command shown does not list extracted paths; use tar’s verbose option -v if you want it to print member names as it extracts.

Compressing a File with gzip

To compress a file, run gzip report.txt. This creates report.txt.gz and normally removes the original report.txt. Add -k as in gzip -k report.txt to keep both the source and compressed file. Gzip compresses each named file separately; use tar first when you need to bundle multiple paths into one archive, then compress that archive to create a .tar.gz file.