How to Compress Single Files Using the Linux gzip Command

When working on a Linux server, disk space is often at a premium, especially when dealing with massive uncompressed log files or raw database exports. While Windows users are accustomed to right-clicking a folder and creating a .zip archive, the Linux command line takes a more modular approach. The standard utility for compressing files in Linux is gzip (GNU zip). It is important to understand that gzip is designed specifically to compress single files, not to bundle entire directories together (that is the job of the tar command). When you run gzip on a file, it replaces the original file with a heavily compressed version ending in the .gz extension.

Compressing a File with gzip

Using gzip is incredibly simple and requires no complex flags for basic operation.

  1. Open your terminal.
  2. Locate the file you want to compress. For example, assume you have a 500MB text file named server_logs.txt.
  3. Type the command: gzip server_logs.txt
  4. Press Enter.

The terminal will not output a confirmation message. However, if you run the ls command to list the directory contents, you will see that server_logs.txt has completely disappeared. In its place is a new file named server_logs.txt.gz. The file has been compressed, and the original uncompressed version has been automatically deleted to save space.

Adjusting the Compression Level

By default, gzip uses a compression level of 6, which offers a good balance between compression speed and file size reduction. However, you can manually adjust this level from 1 to 9 depending on your needs.

  • Level 1 (Fastest): Use this if you are compressing a massive file and don’t want to wait long, but are willing to accept a slightly larger final file size. gzip -1 massive_database.sql
  • Level 9 (Best Compression): Use this if you want the absolute smallest file size possible, regardless of how long the CPU takes to process it. gzip -9 archive_data.csv

Compressing Files While Keeping the Original

In some scenarios, you might want to create a compressed backup of a file but keep the original uncompressed version intact for immediate use. You can force gzip to do this using the -k (keep) flag.

gzip -k important_config.conf

After running this command, you will have both important_config.conf AND important_config.conf.gz sitting in your directory.

Decompressing a gzip File

When you need to read or execute the compressed file, you must reverse the process. The standard tool for this is gunzip (which is technically just a shortcut for running gzip -d).

  1. To extract the file, type: gunzip server_logs.txt.gz
  2. Press Enter.

The .gz archive will be deleted, and the original, fully restored server_logs.txt will take its place.

Get the best tech tips delivered straight to your inbox.

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