Skip to main content
In this article, you will learn how to compress and uncompress files in Linux. File compression reduces storage space and speeds up file transfers between systems. Most Linux distributions come with at least three built-in compression utilities: gzip, bzip2, and xz.

Basic Compression with gzip and bzip2

Below is a simple example of compressing files with gzip and bzip2:
When these commands are executed, each file is compressed into a new file (e.g., file1 becomes file1.gz and file2 becomes file2.bz2) and the original file is automatically deleted.

Decompressing Files

To restore the original files, use the corresponding decompression commands for gzip, bzip2, and xz:

Retaining the Original File

Sometimes you may want to compress a file without deleting the original. Most Linux compression utilities offer an option to keep the original file. Use the --help flag to check available options:
Using the --keep (or -k) option retains the original file when compressing.
Here are examples of using the --keep option:

Inspecting Compressed File Contents

If you need to view the contents of a compressed file, you can use the --list option. For example:

Working with the zip Utility

While gzip, bzip2, and xz are popular for compressing individual files, the zip utility can compress an entire directory or multiple files into a single archive.

Archiving a Single File with zip

Compressing an Entire Directory

To extract a zip archive, use the following command:

Using tar for Archiving and Compression

Unlike zip, utilities like gzip do not support compressing multiple files into a single archive. Instead, tar is commonly used to bundle files together before compression.

Creating a Tar Archive and Compressing it

If you want to keep the uncompressed tar archive along with the compressed file, use the --keep option:
Modern versions of tar allow you to create and compress an archive in a single step. The compression utility is automatically selected based on the file extension:
During extraction, tar automatically detects the compression type, eliminating the need to specify a decompression method.

Summary

This article provided an overview of various techniques for compressing and uncompressing files in Linux using utilities such as gzip, bzip2, xz, and zip. You also learned how to use tar for archiving and compressing multiple files. These methods help efficiently manage file sizes and streamline file transfers. For more detailed information on Linux file management and compression techniques, explore additional resources like Kubernetes Basics or visit Linux Documentation.

Watch Video