Archives and disk tools

Linux commands: gunzip

Learn how the Linux gunzip command decompresses gzipped .gz files, removing the extension, or extracts to a new filename using gunzip -c with redirection.

gunzip decompresses files compressed in the gzip format, the ones ending in .gz. It’s the counterpart of the gzip command we saw in the previous lesson. The two are the same program wearing different names: gunzip is gzip with the -d (decompress) option always turned on.

You call it like this:

gunzip filename.gz

This decompresses the data, removes the .gz extension, and puts the result in the filename file.

Notice the compressed file is gone afterwards. Check with ls:

ls
# filename

If a filename file already exists, gunzip won’t overwrite it quietly. In a terminal it asks you first. In a script it prints gunzip: filename already exists -- skipping and exits with status 1. Add -f when you want to force the overwrite.

If you want to keep the .gz file around too, add the -k option:

gunzip -k filename.gz
# now you have both filename and filename.gz

You can extract to a different filename using output redirection with the -c option:

gunzip -c filename.gz > anotherfilename

-c writes the decompressed data to standard output instead of to a file, and the > redirection saves it wherever you want. The original .gz file stays untouched in this case too.

Before extracting, you can check what you will get with -l, which lists the compressed and uncompressed sizes. Here’s what it prints for a gzipped log file on my machine:

gunzip -l access.log.gz
#   compressed uncompressed  ratio uncompressed_name
#       212869       588895  63.8% access.log

I use this before extracting something big, because the uncompressed size can be several times larger than the file I downloaded. Better to know before I fill up the disk.

Two failures you will run into sooner or later. First, running gunzip notes on a file without a recognized extension stops with gunzip: notes: unknown suffix -- ignored. gunzip only processes files it knows gzip created, so rename the file to end in .gz if you are sure it’s gzipped.

Second, gzip compresses a single file, never a folder. When you see project.tar.gz, that is a tar archive that was gzipped afterwards. Running gunzip project.tar.gz gives you project.tar, and you unpack that with the tar command. Or let tar -xzf project.tar.gz do both steps at once, which is what we’ll see in the next lesson.

The gunzip command works on Linux, macOS, WSL, and anywhere you have a UNIX environment.

Lesson completed