🗜️ gunzip Command

Decompress gzip-compressed files in Linux/UNIX systems

Overview

The gunzip command is used to decompress files that have been compressed with gzip. It's essentially a wrapper around gzip -d and provides a convenient way to restore compressed files to their original form. By default, gunzip removes the .gz extension and replaces the compressed file with the decompressed version.

Basic Syntax

gunzip [OPTIONS] filename.gz

Common Options

Option Description
-c Write output to stdout, keep original file
-f Force decompression, overwrite existing files
-k Keep the compressed file (don't delete)
-l List compression information for each file
-r Recursively decompress directories
-t Test compressed file integrity
-v Verbose mode, show file names and compression ratios
-q Quiet mode, suppress warnings

Detailed Examples

Example 1: Basic File Decompression

Decompress a single gzip file, replacing it with the uncompressed version:

gunzip backup.tar.gz

Result: The file backup.tar.gz is decompressed to backup.tar, and the .gz file is removed.

Note: This is the most common usage. The original compressed file is deleted after successful decompression.
Example 2: Keep Original Compressed File

Decompress a file while preserving the original compressed version:

gunzip -k logfile.log.gz

Result: Creates logfile.log while keeping logfile.log.gz intact.

Tip: This is useful when you need to keep the compressed file for archival purposes or when you're unsure if you'll need the compressed version again.
Example 3: Decompress to stdout

View or pipe decompressed content without creating a file:

gunzip -c access.log.gz | grep "ERROR"

# Or save to a different location
gunzip -c data.gz > /tmp/data.txt

Result: The compressed file remains unchanged, and output is sent to stdout for further processing or redirection.

Tip: This is extremely useful for processing log files without using disk space, or for piping data through multiple commands.
Example 4: List Compression Information

View details about compressed files without decompressing them:

gunzip -l database_backup.sql.gz

# Sample output:
#          compressed        uncompressed  ratio uncompressed_name
#             1234567            12345678  90.0% database_backup.sql

Result: Displays compressed size, uncompressed size, compression ratio, and original filename.

Note: This helps you estimate disk space needed before decompressing and verify compression effectiveness.
Example 5: Test File Integrity

Verify that a compressed file is not corrupted before decompressing:

gunzip -t important_data.gz

# Test multiple files
gunzip -t *.gz

Result: Returns exit status 0 if file is valid, non-zero if corrupted. No output on success.

Tip: Always test critical compressed files (especially after network transfers) before decompressing to avoid data loss.
Example 6: Verbose Decompression

Show detailed information during decompression:

gunzip -v report.pdf.gz

# Sample output:
# report.pdf.gz:    87.2% -- replaced with report.pdf

Result: Displays filename, compression ratio, and action taken for each file.

Note: Verbose mode is helpful for monitoring batch operations and confirming successful decompression.
Example 7: Force Overwrite Existing Files

Decompress even when the target file already exists:

gunzip -f config.conf.gz

# Useful in scripts
gunzip -fv *.gz

Result: Overwrites existing config.conf without prompting for confirmation.

Warning: Use with caution! This will overwrite existing files without asking. Always ensure you have backups of important data.
Example 8: Recursive Directory Decompression

Decompress all gzip files in a directory tree:

gunzip -r /var/log/archives/

# With verbose output
gunzip -rv /home/user/backups/

Result: Traverses all subdirectories and decompresses every .gz file found.

Tip: Combine with -k to keep originals: gunzip -rk /path/to/archive/
Example 9: Batch Decompression with Wildcards

Decompress multiple files matching a pattern:

# Decompress all .gz files in current directory
gunzip *.gz

# Decompress specific pattern
gunzip log_2024*.gz

# Keep originals while batch processing
gunzip -k backup_*.tar.gz

Result: Processes all matching files in a single command.

Note: Shell wildcards are expanded before gunzip runs, so you're effectively running the command on each file.
Example 10: Advanced Usage - Processing and Recompressing

Decompress, process, and recompress in a pipeline:

# View and search without creating temp files
gunzip -c access.log.gz | grep "404" | less

# Decompress, modify, and recompress
gunzip -c data.csv.gz | sed 's/oldvalue/newvalue/g' | gzip > data_modified.csv.gz

# Compare two compressed files
diff <(gunzip -c file1.gz) <(gunzip -c file2.gz)

# Extract specific lines from compressed file
gunzip -c large.log.gz | sed -n '1000,2000p' > extract.log

Result: Enables complex operations on compressed data without intermediate disk writes.

Tip: Process substitution <(...) and piping with gunzip -c are powerful techniques for working efficiently with compressed data.

Important Notes

  • Default Behavior: gunzip removes the .gz file after successful decompression unless -k or -c is used
  • Permissions Preserved: Original file permissions, ownership, and timestamps are preserved
  • Extension Handling: gunzip recognizes .gz, .z, -gz, -z, and _z extensions
  • Symbolic Links: By default, gunzip will not decompress symbolic links; use -f to force
  • Exit Status: Returns 0 on success, 1 on error, 2 if warning occurred

Common Use Cases

  • Log Analysis: Decompress rotated log files for investigation
  • Software Installation: Extract source code tarballs (gunzip package.tar.gz then tar xf package.tar)
  • Backup Restoration: Restore compressed backup files
  • Data Processing: Extract compressed data files for analysis
  • Archive Management: Prepare compressed files for further processing

Related Commands

Command Purpose
gzip Compress files (complement to gunzip)
zcat View compressed files without decompressing (same as gunzip -c)
tar Archive utility, often used with gzip (tar.gz files)
bzip2/bunzip2 Alternative compression format with better compression ratios
xz/unxz Modern compression with excellent compression ratios
zip/unzip Cross-platform archive format

Best Practices

Before Decompressing:
  • Check available disk space with df -h
  • Use gunzip -l to see decompressed size
  • Test file integrity with gunzip -t for critical data
  • Consider using -k to keep originals of important files
Cautions:
  • gunzip will overwrite existing files without -f, but will prompt in interactive mode
  • Watch disk space when decompressing large files
  • Corrupted .gz files may produce incomplete output—always verify critical data
  • Network file systems may have issues with very large files

Quick Reference Script

#!/bin/bash
# Practical gunzip usage examples

# Check if file is valid before decompressing
if gunzip -t myfile.gz 2>/dev/null; then
    echo "File is valid, decompressing..."
    gunzip -v myfile.gz
else
    echo "File is corrupted!"
    exit 1
fi

# Decompress all logs, keep originals, show progress
gunzip -kv /var/log/*.gz

# Process compressed log without creating temp file
gunzip -c access.log.gz | awk '{print $1}' | sort | uniq -c

# Safe decompression function
safe_decompress() {
    local file="$1"
    if [ -f "$file" ]; then
        gunzip -t "$file" && gunzip -v "$file" || echo "Error with $file"
    fi
}