Skip to content

RHCSA - Understand and Use Essential Tools: Compression & Decompression Using gzip

gzip Overview

gzip is a file compression and decompression tool used in Linux systems. The gzip command reduces the size of the named files using Lempel-Ziv coding (LZ77). gzip replaces the original file with a compressed version that has a .gz extension. Compressed files can be significantly smaller in size, saving storage space and reducing file transfer times.

Create a Practice File

To create a file for practicing gzip with, run:

Creating files with data using output from the dmesg & journalctl commands:

dmesg       > gzip-test-default.txt
journalctl >> gzip-test-default.txt
ls -lR /   >> gzip-test-default.txt 2> /dev/null

cp gzip-test-default.txt gzip-test-fast.txt
cp gzip-test-default.txt gzip-test-best.txt

Note down the original size of the gzip-test-default.txt file as this will be used to compare file sizes post compression in later exercises.

ls -lh gzip-test-default.txt

21M in my case.

-rw-r--r--. 1 user1 user1 21M Jun 26 19:09 gzip-test-default.txt

Compression Using gzip

When using gzip you can use different flags to regulate the speed of compression (-#, --fast, & --best). Where -1 or --fast indicates the fastest compression method (less compression) and -9 or --best indicates the slowest compression method (best compression). The default compression level is -6 (which is biased towards high compression at expense of speed).

Using the -v flag will show the compression percentage as well as the new file name.

Using gzip with default compression:

gzip -v gzip-test-default.txt

Using gzip with fastest compression:

gzip -v --fast gzip-test-fast.txt

Using gzip with the best compression:

gzip -v --best gzip-test-best.txt

Comparing compressed file sizes:

ls -lh gzip-test-*.txt.gz

In my case we can see that --best had a slight improvement over the default but a significant improvement over the --fast option.

-rw-r--r--. 1 user1 user1 1.9M Jun 26 19:17 gzip-test-best.txt.gz
-rw-r--r--. 1 user1 user1 2.0M Jun 26 19:17 gzip-test-default.txt.gz
-rw-r--r--. 1 user1 user1 2.5M Jun 26 19:17 gzip-test-fast.txt.gz

Decompression Using gzip/gunzip

There are two ways to decompress files that were compressed using gzip. You can either use gzip itself with the -d, --decompress or --uncompress options, or you can use the gunzip command.

Using the -v flag will show the compression percentage as well as the new file name.

Using gzip -d to decompress a file:

gzip -v -d gzip-test-default.txt.gz

Using gzip --decompress to decompress a file:

gzip -v --decompress gzip-test-fast.txt.gz

Using gunzip to decompress a file:

gunzip -v gzip-test-best.txt.gz