How to Compress Files in Linux Using the gzip Command

Managing server storage space is a critical task for any Linux administrator. Massive raw text files, such as database backups (SQL dumps) or years of server access logs, can rapidly consume a hard drive. Because plain text is highly repetitive, it is incredibly easy to compress. The standard tool for compressing individual files in the Linux terminal is the gzip command.

The Basics of the gzip Command

The gzip (GNU zip) utility uses the DEFLATE algorithm to shrink files, often reducing text-based files by up to 80% of their original size.

To compress a file, simply open your terminal and type gzip followed by the name of the file:

gzip backup.sql

Press Enter. The command will execute silently. If you run an ls command to view the directory contents, you will notice something important: the original backup.sql file is gone.

By default, gzip replaces the original, massive file with a smaller, compressed version that has a .gz extension appended to the end (e.g., backup.sql.gz).

How to Keep the Original File

If you are compressing a file to email it to a colleague, but you still need to actively read the original uncompressed file on your own server, the default behavior of deleting the source file is frustrating. You can force gzip to leave the original file alone by using the -k (keep) flag.

gzip -k backup.sql

This will generate the new backup.sql.gz archive, while safely leaving the original backup.sql file exactly where it was.

How to Decompress (Unzip) a File

When you need to reverse the process and restore the file to its original, readable state, you do not use the gzip command. Instead, you use its sister command, gunzip.

gunzip backup.sql.gz

Just like the compression process, this will extract the raw data, recreate backup.sql, and automatically delete the .gz archive to clean up the directory.

Note: The gzip command is designed to compress individual files, not entire folders. If you want to compress an entire directory containing multiple files, you must first bundle them together using the tar command, creating a .tar.gz archive.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.

Receive our best articles and tips delivered straight to your inbox.