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
-rw-r--r-- 1 user user 50M myfile.txt
-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).
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.
-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.
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
-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)
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.
/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/
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"
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.
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 stdoutgzip -9- Compress with best ratio| ssh- Pipe to remote systemcat > /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.