• Posted: 16-07-2025
  • Last Updated: 26-07-2025
  • Category: Server Guides

Compressing files saves disk space and makes data transfers faster. This article will guide you through the most common command-line tools for compressing and decompressing files and directories in the Linux operating system.

Understanding the Core Concepts: TAR vs. GZIP/BZIP2/XZ

To properly use the commands, you need to understand two distinct concepts:

  • tar (Tape Archive): This is an archiving tool. It bundles multiple files and directories into a single file (e.g., backup.tar) but does not compress it.
  • gzip, bzip2, xz: These are compression tools. They compress a single file to reduce its size (e.g., compressing backup.tar into backup.tar.gz).

Therefore, a .tar.gz file is essentially a group of files bundled by tar and then compressed by gzip to save space.

1. The .tar.gz (or .tgz) Format

This is the most popular compression format on Linux, using the gzip algorithm.

Compressing Files and Directories

Use the -z flag in the tar command to compress directly.

# Syntax: tar -czvf [archive-name.tar.gz] [directory-or-files-to-compress]
tar -czvf archive.tar.gz /home/user/public_html

Decompressing Files

Use the -x (extract) flag to decompress.

# Syntax: tar -xzvf [archive-name.tar.gz]
tar -xzvf archive.tar.gz

# Extract to a specific directory
tar -xzvf archive.tar.gz -C /home/user/backups

Viewing the Contents of a Compressed File

Use the -t (list) flag to view the contents without decompressing.

tar -tzvf archive.tar.gz

2. The .tar.bz2 Format

This format uses the bzip2 algorithm, which often provides slightly better compression than .gz but takes more time.

Compressing Files and Directories

Use the -j flag.

# Syntax: tar -cjvf [archive-name.tar.bz2] [data-to-compress]
tar -cjvf archive.tar.bz2 /home/user/public_html

Decompressing Files

Use the -j flag.

tar -xjvf archive.tar.bz2

3. The .zip Format

This format is very common and highly compatible with Windows. The zip and unzip commands handle both archiving and compression in one step.

Compressing Files and Directories

Use the zip command with the -r (recursive) flag to include subdirectories.

# Syntax: zip -r [archive-name.zip] [data-to-compress]
zip -r archive.zip /home/user/public_html

Decompressing Files

unzip archive.zip

# Extract to a specific directory
unzip archive.zip -d /home/user/backups

Viewing the Contents of a Compressed File

unzip -l archive.zip

Explanation of TAR Command Flags

  • -c (create): Create a new archive.
  • -x (extract): Extract files from an archive.
  • -t (list): List the contents of an archive.
  • -v (verbose): Show the progress in detail.
  • -f (file): Specify the archive file name to work with.
  • -z: Use the gzip compression algorithm.
  • -j: Use the bzip2 compression algorithm.
  • -C: Specify a target directory to extract files into.
Share:
Rating:

( Total: 1 ratings. Average 5, scale: 1 to 5 )