gzip Command Reference Guide

Compress and decompress files with gzip compression

Overview

Purpose

The gzip command compresses files using the DEFLATE compression algorithm. It reduces file size significantly, making it ideal for storage and network transfer. Most commonly used for single-file compression; combine with tar for multiple files.

Basic Syntax

gzip [options] filename

Key Concept

Gzip replaces the original file with a compressed version (.gz extension). Use gunzip or gzip -d to decompress. For archives with multiple files, use tar with gzip: tar -czf archive.tar.gz files/

Compression Concepts

Compression Levels

-1 (fastest, worst compression) through -9 (slowest, best compression). Default is -6. Higher compression (-9) takes more CPU time but creates smaller files.

File Replacement

By default, gzip replaces the original file with the compressed version. Use -c to write to stdout and keep the original, or -k to keep the original file.

Compression Level Speed Ratio Use Case
-1 (fastest) Very fast Poor Real-time compression
-6 (default) Balanced Good Most common
-9 (best) Slow Best Archival, storage

Common Options

Option Description
-c Write to stdout, don't modify original
-d Decompress (same as gunzip)
-k Keep original file (don't delete)
-v Verbose - show compression details
-r Recursively compress directory
-t Test compressed file integrity
-# Compression level (1-9)

10 Detailed Examples

1
Basic File Compression
Before
ls -lh myfile.txt
-rw-r--r-- 1 user user 50M myfile.txt
Compress file
gzip myfile.txt
After
ls -lh myfile.txt.gz
-rw-r--r-- 1 user user 5M myfile.txt.gz

What This Does:

Compresses myfile.txt and replaces it with myfile.txt.gz. The original file no longer exists. File size reduced from 50MB to 5MB (90% compression on this text data).

Common Usage:

Perfect for log files, backups, and data archival. Compression ratio varies by file type (text compresses well, already-compressed files like PNG don't compress much further).

2
Decompress File
Method 1: gunzip
gunzip myfile.txt.gz
Method 2: gzip -d
gzip -d myfile.txt.gz
[file is decompressed back to myfile.txt]

What This Does:

Decompresses the .gz file back to original. Both gunzip and gzip -d do the same thing. The original .gz file is deleted.

Quick Tip:

gunzip is shorter to type and is the standard decompression tool. Most systems have it as an alias or separate command.

3
Keep Original File with -k
Compress but keep original
gzip -k large_dataset.csv
Check files
ls -lh large_dataset.*
-rw-r--r-- 1 user user 100M large_dataset.csv
-rw-r--r-- 1 user user 10M large_dataset.csv.gz

What This Does:

The -k flag keeps the original file after compression. Useful when you need both compressed and uncompressed versions for compatibility.

Use Case:

Archive original files while providing compressed versions for download/transfer. Backup systems often do this.

4
Compress to stdout with -c
Pipe compressed output
gzip -c myfile.txt | tee backup.gz | wc -c
5242880
Compress and send via SSH
gzip -c large_file.log | ssh remote.host 'cat > /backups/file.log.gz'

What This Does:

The -c flag writes compressed output to stdout instead of creating a .gz file. Allows piping for efficient network transfers or further processing.

Powerful Patterns:

  • Compress and pipe to remote system
  • Compress while monitoring size
  • Compress for direct stdout inspection
5
Compression Levels: Speed vs Ratio
Fastest compression (-1)
time gzip -1 -c large_file.txt > output1.gz
real 0m1.234s
Default compression (-6)
time gzip -6 -c large_file.txt > output6.gz
real 0m3.567s
Best compression (-9)
time gzip -9 -c large_file.txt > output9.gz
real 0m8.234s
Compare file sizes
ls -lh output*.gz
-rw-r--r-- 1 user user 12M output1.gz
-rw-r--r-- 1 user user 10M output6.gz
-rw-r--r-- 1 user user 9.8M output9.gz

What This Shows:

Trade-off between speed and compression ratio. -1 is 6.7x faster than -9 but produces 22% larger file. Choose based on your priorities.

Recommendations:

  • -1 - Real-time logging, streaming
  • -6 - General purpose (default, usually best)
  • -9 - Archival, storage (minimal space premium)
6
Verbose Output with -v
Compress with verbose info
gzip -v *.log
app.log: 83.2% (100M -> 16.8M)
system.log: 72.5% (50M -> 13.7M)
access.log: 68.9% (75M -> 23.4M)

What This Does:

Shows compression details for each file: percentage saved, original size, and compressed size. Useful for monitoring batch operations.

Batch Operations:

Combine with * wildcard to compress multiple files at once. Each file gets its own .gz file.

7
Recursive Directory Compression
Compress all files in directory tree
gzip -r /var/log/
Verify
find /var/log -name "*.gz" | head
/var/log/apache2/access.log.gz
/var/log/apache2/error.log.gz
/var/log/apt/history.log.gz
/var/log/auth.log.gz
/var/log/cron.log.gz

What This Does:

The -r flag recursively compresses all files in directory and subdirectories. Each file individually becomes .gz; directories aren't changed.

Important Note:

-r doesn't create a single archive like tar. It compresses each file individually. For a single compressed archive, use tar: tar -czf archive.tar.gz directory/

8
Test Compressed File Integrity
Test file for corruption
gzip -t backup.tar.gz
[no output = file is OK]
If corrupted:
gzip: backup.tar.gz: invalid compressed data--crc error

What This Does:

Tests the integrity of compressed file without decompressing. Returns success silently or shows error. Critical for verifying backups.

Best Practice:

Always test backups after compression: gzip -t backup.gz && echo "Backup OK" || echo "Backup corrupted"

9
tar with gzip Integration (tar.gz)
Create compressed tar archive
tar -czf backup.tar.gz /home/user/documents/
Extract (gzip handles automatically)
tar -xzf backup.tar.gz
List contents without extracting
tar -tzf backup.tar.gz | head
home/user/documents/file1.txt
home/user/documents/file2.doc
home/user/documents/subdir/file3.pdf

What This Does:

Tar creates archives of multiple files/directories; gzip compresses the result. The combination -z flag automatically handles gzip. Most efficient for backing up directories.

Production Backup Pattern:

tar -czf /backups/daily-$(date +%Y%m%d).tar.gz /critical/data/ creates timestamped compressed backups.

10
Advanced: Piping and Network Transfer
Backup directly to remote system
tar -c /important/data | gzip -9 | ssh backup@archive.local 'cat > /backups/data-$(date +%Y%m%d).tar.gz'
Remote verification
ssh backup@archive.local 'gzip -t /backups/data-*.tar.gz && echo "All backups valid"'

What This Does:

Demonstrates advanced pattern: tar archives, gzip compresses with level 9, piped over SSH to remote system. Creates timestamped backup without local disk overhead.

Breaking Down the Command:

  • tar -c - Create archive, output to stdout
  • gzip -9 - Compress with best ratio
  • | ssh - Pipe to remote system
  • cat > /path/file - Write to remote file
  • $(date +%Y%m%d) - Add timestamp

Production Enterprise Backup:

This pattern scales to terabytes; compressed stream goes directly to network without temporary files.

Comparison: gzip vs Other Compression Tools

Tool Compression Speed Ratio Best For
gzip DEFLATE Fast Good General purpose (most common)
bzip2 Burrows-Wheeler Slower Better Maximum compression
xz LZMA2 Slowest Best Extreme compression (Linux kernels)
zip DEFLATE Fast Good Cross-platform archives

Practical System Administration Scenarios

Log Rotation and Compression

Logrotate typically compresses old logs: compress postrotate /usr/lib/rsyslog/rsyslog-rotate.sh applies gzip to rotated logs automatically.

Backup Strategy

Daily backup: tar -czf /backups/daily-$(date +%Y%m%d).tar.gz /important/data. Weekly: gzip -9 for maximum compression. Test with gzip -t.

Distribution Packages

Most Linux source distributions use .tar.gz format. Extract with: tar -xzf package.tar.gz

Troubleshooting

Problem: File not compressing well

Already-compressed formats (PNG, JPEG, MP4) compress poorly. Text, logs, and data compress best. Check compression ratio with gzip -v.

Problem: Permission denied when decompressing

Check file permissions and target directory: ls -l file.gz. Ensure write access to output directory.

Problem: "unexpected end of file" error

File is corrupted. Test with gzip -t first. Transfer over network may have corrupted the file. Re-download and verify.