How to Compress and Extract Files in Linux

To compress files in Linux, use tar -czvf archive.tar.gz folder/ to create a compressed tar archive, or zip -r archive.zip folder/ for a ZIP file. To extract, use tar -xzvf archive.tar.gz for tar.gz files, or unzip archive.zip for ZIP files. Linux supports multiple compression formats โ€” tar.gz (most common on Linux), zip (cross-platform compatible), bzip2 (better compression), and xz (best compression) โ€” each with its own commands for creating and extracting archives.

Why Compression Matters in Linux

Compression is a daily part of Linux life, whether you realize it or not. Every software package you download through apt or dnf arrives as a compressed archive. Every backup worth its name uses compression to reduce storage needs. Log files get compressed to save disk space. Source code is distributed as compressed tarballs. Files shared across the internet are zipped to speed up transfer. Configuration backups are archived before major changes.

Understanding how to work with compressed archives in Linux is not optional knowledge โ€” it is a core skill that comes up constantly. The good news is that once you understand the underlying concepts and the handful of commands involved, working with archives becomes fast and intuitive.

The one aspect that trips up many Linux beginners is that compression and archiving are technically separate operations, but they are almost always performed together. Archiving bundles multiple files and directories into a single file; compression shrinks that file. Linux handles both steps in one command, but understanding they are distinct helps explain why there are multiple formats and why the commands look the way they do.

This article covers every compression format and tool you are likely to encounter on a Linux system: tar (the universal Linux archive format), gzip, bzip2, and xz (compression algorithms), zip and unzip (cross-platform archives), and 7-Zip (which handles a wide variety of formats). For each tool, you will learn both creation and extraction, with practical examples and explanations of when each is the right choice.

The Concept: Archiving vs. Compression

Before the commands, two concepts deserve clear definition.

Archiving: Bundling Many Files Into One

An archive is a single file that contains multiple files and directories, preserving their structure, names, permissions, and other metadata. The most common Linux archiving tool is tar, which stands for tape archive โ€” its original purpose was backing up data to magnetic tape.

Archiving alone does not reduce file size. A tar archive containing 100 MB of files occupies approximately 100 MB on disk (plus a small amount of metadata overhead). Archiving without compression is useful when you want to bundle files for distribution while maintaining their structure, but storage size is not a concern.

Compression: Reducing File Size

Compression algorithms analyze data and encode it more efficiently, reducing the amount of storage needed. A 100 MB collection of text files might compress to 20 MB โ€” an 80% reduction. Binary data (already-compressed images, videos, or compiled programs) compresses much less, sometimes not at all.

Compression applies to a single stream of data. Standalone compression tools like gzip compress one file at a time โ€” they cannot directly compress a directory.

The Combination: Compressed Archives

The practical solution is to combine both: first create a tar archive (bundling everything into one file), then compress that archive. This is why you see .tar.gz (tar archive, then gzip compression), .tar.bz2 (tar archive, then bzip2 compression), and .tar.xz (tar archive, then xz compression) everywhere on Linux.

Modern tar performs both operations together with a single command, making the two-step process transparent. But understanding that there are two separate steps explains the file extension conventions and what the different flags do.

tar: The Linux Standard

tar is the foundational archiving tool on every Linux system. It is installed by default everywhere and is the format used for distributing Linux software source code, making backups, and creating archives for any purpose.

Creating a tar Archive

The basic structure for creating a compressed tar archive:

$ tar -czvf archive_name.tar.gz files_or_directories

Breaking down the flags:

  • -c โ€” create a new archive
  • -z โ€” compress using gzip (produces .tar.gz or .tgz)
  • -v โ€” verbose: show each file as it is processed
  • -f archive_name.tar.gz โ€” specify the output filename (must come immediately before the filename)

Practical examples:

Archive and compress a single directory:

$ tar -czvf project_backup.tar.gz ~/projects/website/

Archive and compress multiple items:

$ tar -czvf configs.tar.gz ~/.bash.rc ~/.config/.nvim/ ~/.ssh/.config

Archive the current directory:

$ tar -czvf backup.tar.gz .

Archive without verbose output (cleaner for scripts):

$ tar -czf archive.tar.gz ~/Documents/

Extracting a tar.gz Archive

$ tar -xzvf archive.tar.gz

Flags for extraction:

  • -x โ€” extract files from the archive
  • -z โ€” decompress using gzip
  • -v โ€” verbose: show each file as it is extracted
  • -f archive.tar.gz โ€” the archive to extract

Extract to a specific directory:

$ tar -xzvf archive.tar.gz -C /destination/path/

The -C flag specifies where to extract. The destination directory must already exist:

$ mkdir -p ~/restored_files
$ tar -xzvf backup.tar.gz -C ~/restored_files/

Extract without verbose (quiet extraction):

$ tar -xzf archive.tar.gz

Listing Archive Contents Without Extracting

Before extracting an archive, checking its contents is good practice โ€” especially with archives from unknown sources, which might extract unexpected files:

$ tar -tzvf archive.tar.gz

The -t flag lists (table of contents) the archive. The output shows each file with its permissions, owner, size, date, and path:

drwxr-xr-x sarah/sarah   0 2026-02-18 09:22 website/
-rw-r--r-- sarah/sarah 4096 2026-02-17 14:31 website/index.html
-rw-r--r-- sarah/sarah 2048 2026-02-16 11:20 website/style.css
-rw-r--r-- sarah/sarah 8192 2026-02-15 08:45 website/script.js

Extracting Specific Files from an Archive

You can extract individual files or directories from an archive without extracting everything:

$ tar -xzvf archive.tar.gz website/index.html

Extracts only index.html from the archive.

$ tar -xzvf archive.tar.gz website/css/

Extracts only the css/ directory.

The tar.gz vs .tgz Naming

.tar.gz and .tgz are identical formats โ€” both are gzip-compressed tar archives. .tgz is simply a shorter single-extension alternative. Use either; both extract with the same tar -xzvf command.

Better Compression with bzip2 and xz

While gzip is the most common compression algorithm used with tar (and the fastest), bzip2 and xz offer better compression ratios at the cost of speed. For large archives where storage space matters more than time, they are worth using.

tar.bz2 โ€” bzip2 Compression

Replace the -z (gzip) flag with -j (bzip2):

Create a .tar.bz2 archive:

$ tar -cjvf archive.tar.bz2 directory/

Extract a .tar.bz2 archive:

$ tar -xjvf archive.tar.bz2

List contents:

$ tar -tjvf archive.tar.bz2

bzip2 typically produces archives 10โ€“20% smaller than gzip but takes noticeably longer to create and extract. It is a good choice for archives that will be stored long-term and transferred infrequently.

tar.xz โ€” xz Compression (Best Compression)

Replace -z (gzip) with -J (capital J for xz):

Create a .tar.xz archive:

$ tar -cJvf archive.tar.xz directory/

Extract a .tar.xz archive:

$ tar -xJvf archive.tar.xz

List contents:

$ tar -tJvf archive.tar.xz

xz produces the smallest archives of the three algorithms โ€” often 20โ€“40% smaller than gzip โ€” but is the slowest. Linux kernel source code and many software distributions use .tar.xz for official releases because the size reduction significantly speeds up downloads for many users.

tar.zst โ€” Zstandard Compression (Modern, Fast and Small)

Zstandard (zstd) is a newer compression algorithm that offers an excellent speed/compression tradeoff โ€” near-gzip speeds with near-xz compression ratios. It is increasingly common on modern Linux systems, particularly for package management (Arch Linux uses .pkg.tar.zst).

$ tar -c --zstd -f archive.tar.zst directory/
$ tar -x --zstd -f archive.tar.zst

Or on systems with newer tar that auto-detects:

$ tar -caf archive.tar.zst directory/
$ tar -xaf archive.tar.zst

The -a flag (auto-compress) tells tar to choose the compression algorithm based on the archive filename extension โ€” a convenient option when you just want tar to do the right thing.

Compression Format Comparison

FormatExtensionSpeedCompressionBest For
gzip.tar.gz / .tgzFastGoodGeneral use, most compatible
bzip2.tar.bz2ModerateBetterLong-term storage
xz.tar.xzSlowBestOfficial distributions, minimal size
Zstandard.tar.zstFastVery goodModern systems, large backups
zip.zipFastGoodCross-platform, Windows compatibility

Auto-Detection: Let tar Figure It Out

Modern tar (version 1.22+) can automatically detect the compression format when extracting, eliminating the need to remember which flag corresponds to which format:

The universal extraction command:

$ tar -xvf archive.tar.gz      # Works โ€” but you need to know it is gzip
$ tar -xf archive.tar.bz2      # Also works โ€” tar auto-detects bzip2
$ tar -xf archive.tar.xz       # Works โ€” tar auto-detects xz
$ tar -xf archive.tar.zst      # Works โ€” tar auto-detects zstd

When extracting, tar examines the file’s actual contents (magic bytes) rather than relying solely on the extension, so it correctly handles any supported format. The only reliable practice difference: use the appropriate flag when creating archives (since you are specifying what format to use), but for extracting, just tar -xvf filename works for virtually all tar-based archives.

ZIP Files: Cross-Platform Archives

The zip format originated on DOS/Windows and remains the universal cross-platform archive format. Any file you receive from a Windows or macOS user, any web download requiring no special software โ€” these are almost always ZIP files. Linux handles ZIP files natively with the zip and unzip commands.

Installing zip and unzip

Most distributions include unzip by default. zip may need installation:

$ sudo apt install zip unzip    # Ubuntu/Debian
$ sudo dnf install zip unzip    # Fedora/RHEL

Creating ZIP Archives

Compress a single file:

$ zip archive.zip file.txt

Compress multiple files:

$ zip archive.zip file1.txt file2.txt file3.txt

Compress a directory (recursive):

$ zip -r archive.zip directory/

The -r (recursive) flag is essential for directories โ€” without it, zip ignores directory contents.

Compress multiple items with verbose output:

$ zip -rv project.zip ~/projects/website/ README.md

Exclude certain files from a ZIP:

$ zip -r archive.zip directory/ --exclude "*.log" --exclude ".git/*"

Add files to an existing ZIP archive:

$ zip existing_archive.zip new_file.txt

Create a password-protected ZIP:

$ zip -e secure_archive.zip sensitive_file.txt

The -e flag prompts for a password. Note that ZIP’s built-in encryption (ZipCrypto) is weak โ€” for serious security, use 7-Zip with AES-256 encryption.

Extracting ZIP Archives

Extract to the current directory:

$ unzip archive.zip

Extract to a specific directory:

$ unzip archive.zip -d /destination/path/

The destination directory is created automatically if it does not exist (unlike tar’s -C which requires a pre-existing directory).

List ZIP contents without extracting:

$ unzip -l archive.zip

Output:

Archive:  archive.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
     4096  02-18-2026 09:22   website/index.html
     2048  02-17-2026 14:31   website/style.css
---------                     -------
     6144                     2 files

Extract specific files:

$ unzip archive.zip website/index.html

Extract without overwriting existing files:

$ unzip -n archive.zip

Preview (test) the archive without extracting:

$ unzip -t archive.zip

Tests the archive’s integrity by verifying checksums without writing any files.

Overwrite all without prompting:

$ unzip -o archive.zip

gzip, bzip2, and xz as Standalone Tools

While usually used alongside tar, the compression tools can also work directly on individual files.

gzip: Compress and Decompress Single Files

Compress a file (replaces original with .gz version):

$ gzip large_file.txt
# Results in large_file.txt.gz (original is gone)

Compress but keep the original:

$ gzip -k large_file.txt
# Results in large_file.txt.gz AND large_file.txt

Decompress:

$ gzip -d large_file.txt.gz
# Restores large_file.txt (removes .gz file)

Or equivalently:

$ gunzip large_file.txt.gz

View compression information:

$ gzip -l large_file.txt.gz
         compressed        uncompressed  ratio uncompressed_name
               4821               16384  70.6% large_file.txt

Compress with maximum compression (slower but smaller):

$ gzip -9 large_file.txt

Compress with fastest compression (larger but faster):

$ gzip -1 large_file.txt

View a .gz file without decompressing:

$ zcat large_file.txt.gz
$ zless large_file.txt.gz    # Page through it
$ zgrep "pattern" large_file.txt.gz    # Search inside without extracting

bzip2 and bunzip2

Works similarly to gzip but produces smaller files:

$ bzip2 file.txt              # Creates file.txt.bz2, removes original
$ bzip2 -k file.txt           # Keep original
$ bzip2 -d file.txt.bz2       # Decompress
$ bunzip2 file.txt.bz2        # Equivalent to bzip2 -d
$ bzcat file.txt.bz2          # View without decompressing
$ bzgrep "pattern" file.txt.bz2

xz and unxz

$ xz file.txt                 # Creates file.txt.xz, removes original
$ xz -k file.txt              # Keep original
$ xz -d file.txt.xz           # Decompress
$ unxz file.txt.xz            # Equivalent to xz -d
$ xzcat file.txt.xz           # View without decompressing
$ xzgrep "pattern" file.txt.xz

Set compression level (0-9, default is 6):

$ xz -9 large_file.txt        # Maximum compression (very slow)
$ xz -0 large_file.txt        # Minimal compression (fastest)

7-Zip: The Swiss Army Knife of Compression

7-Zip (7z on Linux) handles an enormous variety of archive formats and is particularly useful when you encounter less common formats or need the best possible compression ratio. Install it:

$ sudo apt install 7zip         # Ubuntu 22.04+
$ sudo apt install p7zip-full   # Older Ubuntu/Debian
$ sudo dnf install p7zip p7zip-plugins  # Fedora

7-Zip Commands

Create a 7z archive (7-Zip’s native format with excellent compression):

$ 7z a archive.7z directory/

Create with maximum compression:

$ 7z a -mx=9 archive.7z directory/

Extract:

$ 7z x archive.7z

The x command extracts with full paths. The e command extracts all files to the current directory without preserving directory structure.

Extract to a specific directory:

$ 7z x archive.7z -o/destination/path/

List archive contents:

$ 7z l archive.7z

Test archive integrity:

$ 7z t archive.7z

Extract other formats with 7z:

7-Zip reads virtually every archive format, making it invaluable when you receive unusual files:

$ 7z x archive.rar          # RAR archives
$ 7z x archive.7z           # 7-Zip archives
$ 7z x archive.zip          # ZIP archives
$ 7z x archive.tar.gz       # tar.gz
$ 7z x installer.exe        # Windows installers (self-extracting archives)
$ 7z x disk_image.iso       # ISO disc images

Handling .gz Log Files

Linux systems generate compressed log files automatically โ€” logrotate compresses old logs with gzip, resulting in files like syslog.2.gz, auth.log.3.gz. Working with these directly without decompressing to disk is efficient and clean.

View a compressed log file:

$ zcat /var/.log/syslog.2.gz | less

Search inside a compressed log:

$ zgrep "error" /var/.log/syslog.2.gz
$ zgrep -i "authentication failure" /var/.log/auth.log.*.gz

Search across multiple compressed log files:

$ zcat /var/.log/syslog.*.gz | grep "disk" | tail -50

This decompresses all matching logs in a pipeline, searches for disk-related messages, and shows the last 50 matches โ€” all without creating any temporary files on disk.

Practical Scenarios

Creating a Project Backup Before a Major Change

Before making significant changes to a project, archive the current state:

$ cd ~/projects
$ tar -czvf website_backup_$(date +%Y%m%d).tar.gz website/

$(date +%Y%m%d) inserts the current date (e.g., 20260218) into the filename, creating uniquely named backups like website_backup_20260218.tar.gz.

Creating a Compressed Archive Excluding Unnecessary Files

For a project with a virtual environment and git history that should not be archived:

$ tar -czvf project.tar.gz myproject/ \
    --exclude="myproject/.git" \
    --exclude="myproject/.venv" \
    --exclude="myproject/__pycache__" \
    --exclude="myproject/*.pyc"

The --exclude option takes a pattern (similar to .gitignore) and skips matching files.

Checking What Is in a Downloaded Archive Before Extracting

Always inspect an unfamiliar archive before extracting โ€” some archives extract to the current directory flooding it with files, while well-behaved archives extract into a subdirectory:

$ tar -tzf downloaded_software.tar.gz | head -20

If all paths start with software-1.0/, the archive extracts neatly into one directory. If you see bare filenames like Makefile, README, src/main.c, the archive will extract directly to the current directory โ€” extract to a new subdirectory instead:

$ mkdir downloaded_software && tar -xzf downloaded_software.tar.gz -C downloaded_software/

Transferring Files Efficiently Over SSH

When copying many small files to a remote server, compressing them first dramatically reduces transfer time:

# On your local machine
$ tar -czvf transfer.tar.gz ~/projects/website/

# Copy the compressed archive
$ scp transfer.tar.gz user@server:/home/.user/

# On the server
$ tar -xzvf transfer.tar.gz

Or in one pipeline (compress, transfer, and extract without an intermediate file):

$ tar -cz ~/projects/website/ | ssh user@server "cd /var/www && tar -xz"

Decompressing Unknown Archives

When you receive an archive and are not sure what tool to use:

Step 1: Check the file extension โ€” most archives are named with their format (.tar.gz, .zip, .7z, etc.)

Step 2: Use file to identify the format regardless of extension:

$ file unknown_archive
unknown_archive: Zip archive data, at least v2.0 to extract

or:

$ file mysterious_file
mysterious_file: gzip compressed data, from Unix, last modified: Tue Feb 18 09:22:00 2026

Step 3: Use the appropriate tool based on what file reports.

Step 4: When in doubt, try 7z โ€” it handles nearly every archive format:

$ 7z x unknown_archive

Quick Reference: Compression Commands

Creating Archives

FormatCreate Command
.tar.gztar -czvf archive.tar.gz directory/
.tar.bz2tar -cjvf archive.tar.bz2 directory/
.tar.xztar -cJvf archive.tar.xz directory/
.tar.zsttar -c --zstd -f archive.tar.zst directory/
.zipzip -r archive.zip directory/
.gz (single file)gzip -k file.txt
.bz2 (single file)bzip2 -k file.txt
.xz (single file)xz -k file.txt
.7z7z a archive.7z directory/

Extracting Archives

FormatExtract Command
.tar.gz / .tgztar -xzvf archive.tar.gz
.tar.bz2tar -xjvf archive.tar.bz2
.tar.xztar -xJvf archive.tar.xz
Any tar formattar -xvf archive.tar.* (auto-detect)
.zipunzip archive.zip
.gz (single file)gzip -d file.gz or gunzip file.gz
.bz2 (single file)bzip2 -d file.bz2 or bunzip2 file.bz2
.xz (single file)xz -d file.xz or unxz file.xz
.7z / .rar / .iso7z x archive

Listing Archive Contents

FormatList Command
Any tar formattar -tvf archive.tar.*
.zipunzip -l archive.zip
.7z / others7z l archive

Conclusion: A Format for Every Need

Linux’s compression ecosystem is rich with options โ€” each format representing a tradeoff between speed, compression ratio, compatibility, and feature set. The pattern that serves most users well is straightforward: use .tar.gz for Linux-to-Linux archiving where speed and compatibility matter; use .tar.xz when creating distributions or archives where minimum size is critical; use .zip when sharing with Windows or macOS users who may not have tar; and use 7z when you need to handle unusual formats or want the best compression ratio for long-term storage.

The commands themselves are not complicated once you understand the flag patterns. tar -czvf creates, tar -xzvf extracts, tar -tzvf lists โ€” just change the middle letter for bzip2 (j) or xz (J). The zip/unzip pair follows straightforward conventions. And 7z a/7z x handles everything else.

With these tools confidently in hand, you can handle any compression task Linux throws at you โ€” from quick one-off archives to automated backup scripts to decoding whatever unusual format someone sends your way.

Hot this week

Introduction to Linux Text Editors: nano and gedit for Beginners

Learn to use Linux text editors nano and gedit for beginners. Edit config files with nano in the terminal, use gedit graphically, and understand when to use each.

Anthropic Secures $19 Billion Long-Term Data Centre Agreement to Scale AI Infrastructure

Anthropic has signed a $19 billion long-term data centre agreement with TeraWulf to secure 401 megawatts of dedicated AI compute in Kentucky.

Chinese AI Models Now Capture 46% of Enterprise API Usage on US Developer Platforms

A CNBC investigation using OpenRouter and Vercel data reveals that Chinese AI models have surged from 11% to as much as 46% of weekly API token usage by US companies.

JadePuffer Becomes World’s First Documented Agentic Ransomware and It Needed Only One Human

Cloud security firm Sysdig has published findings on JadePuffer, the first documented case of agentic ransomware.

OpenAI Launches GPT-5.6 Series with Sol, Terra, and Luna Models After US Government Security Review

OpenAI has publicly launched its GPT-5.6 model series, comprising Sol, Terra, and Luna, following a delay ordered by the US government over national security concerns.

Topics

Introduction to Linux Text Editors: nano and gedit for Beginners

Learn to use Linux text editors nano and gedit for beginners. Edit config files with nano in the terminal, use gedit graphically, and understand when to use each.

Anthropic Secures $19 Billion Long-Term Data Centre Agreement to Scale AI Infrastructure

Anthropic has signed a $19 billion long-term data centre agreement with TeraWulf to secure 401 megawatts of dedicated AI compute in Kentucky.

Chinese AI Models Now Capture 46% of Enterprise API Usage on US Developer Platforms

A CNBC investigation using OpenRouter and Vercel data reveals that Chinese AI models have surged from 11% to as much as 46% of weekly API token usage by US companies.

JadePuffer Becomes World’s First Documented Agentic Ransomware and It Needed Only One Human

Cloud security firm Sysdig has published findings on JadePuffer, the first documented case of agentic ransomware.

OpenAI Launches GPT-5.6 Series with Sol, Terra, and Luna Models After US Government Security Review

OpenAI has publicly launched its GPT-5.6 model series, comprising Sol, Terra, and Luna, following a delay ordered by the US government over national security concerns.

Meltio and Phillips Corporation Deploy Hybrid Metal AM System Aboard USS Essex for RIMPAC 2026

Phillips Corporation and Meltio have deployed a containerised hybrid manufacturing system aboard the USS Essex during RIMPAC 2026.

What is a Clock Signal and Why Does Digital Electronics Need It?

Understand clock signals in digital electronics โ€” why they're needed, how they work, oscillator types, clock distribution, frequency vs speed, jitter, duty cycle, and practical circuit examples.

Understanding Shift Registers: Moving Data in Series

Master shift registers completely โ€” SIPO, PISO, SISO, PIPO configurations, 74HC595, 74HC165, serial-to-parallel conversion, LED driving, SPI interfacing, and practical microcontroller design examples.

Related Articles

Popular Categories

spot_imgspot_img