gzip
Overview
The gzip
command compresses files using the GNU zip compression algorithm. It’s one of the most common compression tools in Linux systems.
Syntax
gzip [options] [file...]
gunzip [options] [file...]
zcat [file...]
Common Options
Option | Description |
---|---|
-c |
Write to stdout |
-d |
Decompress |
-f |
Force overwrite |
-k |
Keep original files |
-l |
List compressed file info |
-r |
Recursive operation |
-t |
Test integrity |
-v |
Verbose output |
-1 to -9 |
Compression level |
-n |
No timestamp/name |
Compression Levels
Level | Description |
---|---|
-1 |
Fastest compression |
-6 |
Default compression |
-9 |
Best compression |
--fast |
Same as -1 |
--best |
Same as -9 |
Key Use Cases
- Compress files to save space
- Prepare files for transfer
- Archive log files
- Reduce backup sizes
- Web server content compression
Examples with Explanations
Example 1: Basic Compression
gzip file.txt
Compresses file.txt to file.txt.gz and removes original
Example 2: Keep Original File
gzip -k file.txt
Compresses file but keeps the original
Example 3: Decompress File
gunzip file.txt.gz
Decompresses file.txt.gz back to file.txt
Understanding Compression
Compression ratios: - Text files: 60-80% reduction - Binary files: 10-50% reduction - Already compressed: minimal reduction - Log files: excellent compression
Common Usage Patterns
Compress with best ratio:
gzip -9 largefile.txt
Compress to stdout:
gzip -c file.txt > file.txt.gz
Recursive compression:
gzip -r directory/
Advanced Operations
Test file integrity:
gzip -t file.txt.gz
List file information:
gzip -l file.txt.gz
Force compression:
gzip -f file.txt
Performance Analysis
- CPU intensive operation
- Higher compression levels use more CPU
- Memory usage is minimal
- I/O reduction benefits network transfers
- Consider compression level vs time trade-offs
File Extensions
Extension | Description |
---|---|
.gz |
Standard gzip |
.z |
Compress format |
.Z |
Old compress format |
.tgz |
Tar + gzip |
Additional Resources
Best Practices
- Use appropriate compression levels
- Keep originals for critical files
- Test compressed files
- Consider disk space vs CPU trade-offs
- Use with tar for directories
Integration Examples
With tar:
tar -czf archive.tar.gz directory/
Compress logs:
gzip /var/log/*.log
Pipeline compression:
cat largefile | gzip > compressed.gz
Troubleshooting
- File already exists errors
- Insufficient disk space
- Permission issues
- Corrupted compressed files
- Compression ratio expectations
Security Considerations
- Compressed files can hide malware
- Verify file integrity after compression
- Be cautious with recursive operations
- Check available disk space
- Validate decompressed content