When working with log files, database backups, or large text documents on an Ubuntu Linux server, storage space can fill up quickly. Compressing these files is a critical skill for any system administrator. While there are many compression tools available in Linux, gzip (GNU zip) is one of the oldest, most standard, and most widely used utilities for single-file compression.
The Basic gzip Command
The gzip command is incredibly simple to use. Its primary function is to take a file, compress it, and replace the original file with the new, smaller compressed version.
Suppose you have a large log file named server_logs.txt. To compress it, open your terminal and type:
gzip server_logs.txt
Once you press Enter, the system will process the file. If you run the ls command to list the directory contents afterward, you will notice that server_logs.txt has disappeared. In its place is a new file named server_logs.txt.gz. The .gz extension indicates that the file has been successfully compressed.
Keeping the Original File (The -k Flag)
By default, gzip destroys the original file to save space. However, you often want to create a compressed backup while keeping the original file intact for immediate use. You can do this by using the -k (keep) flag.
gzip -k server_logs.txt
After running this command, both server_logs.txt and server_logs.txt.gz will exist in your directory.
Controlling the Compression Ratio (Flags -1 to -9)
The gzip utility allows you to balance speed against the final file size using a numeric scale from 1 to 9.
- -1 (Fastest): Compresses the file very quickly, but the resulting file won’t be as small as it could be.
- -6 (Default): The standard balance between speed and compression. If you use no flags, gzip defaults to -6.
- -9 (Best): Uses maximum CPU power to squeeze the file as small as physically possible. This takes the longest time, especially on massive files.
To compress a file using the maximum possible compression, use the -9 flag:
gzip -9 database_backup.sql
How to Decompress the File (gunzip)
When you eventually need to read or use the file again, you must decompress it. You do this using the companion command, gunzip.
gunzip server_logs.txt.gz
Just like the compression process, this will extract the data, restore the original server_logs.txt file, and delete the .gz archive. If you want to decompress the file but keep the compressed archive as a backup, simply use the keep flag again: gunzip -k server_logs.txt.gz.