Lesson 2: The Compressor (Archives & Backups)
Servers generate mountains of data — logs, configs, databases. You need to compress, archive, and transfer these efficiently. Master the art of squeezing files and you'll save bandwidth, storage, and time.
tar — The Tape Archiver
tar bundles multiple files into a single archive. Combined with compression, it's the standard backup tool.
Creating Archives:
tar -czf archive.tar.gz folder/ # Create compressed archive
tar -cf archive.tar folder/ # Create without compression
Reading Archives:
tar -tzf archive.tar.gz # List contents without extracting
Extracting Archives:
tar -xzf archive.tar.gz # Extract to current directory
tar -xzf archive.tar.gz -C /tmp/ # Extract to a specific directory
Decoding the Flags
| Flag | Meaning |
|------|---------|
| -c | Create a new archive |
| -x | Extract files from archive |
| -t | List contents of archive |
| -z | Use gzip compression |
| -f | Specify the filename |
| -v | Verbose (show progress) |
Other Compression Tools
| Tool | Extension | Best For |
|------|-----------|----------|
| gzip | .gz | Fast compression, standard Linux |
| bzip2 | .bz2 | Better compression, slower |
| zip/unzip | .zip | Cross-platform compatibility |
| xz | .xz | Best compression ratio |
gzip large_log.txt # Compresses → large_log.txt.gz
gunzip large_log.txt.gz # Decompresses back
zip backup.zip file1 file2 # Create zip archive
unzip backup.zip # Extract zip
Backup Strategy
A simple daily backup script:
#!/bin/bash
DATE=$(date +%Y-%m-%d)
tar -czf "/backups/server-$DATE.tar.gz" /etc /var/log /home
echo "Backup created: server-$DATE.tar.gz"
Mission Objective
Practice archiving and restoring data:
- Pack it up: Create a compressed archive with
tar -czf backup.tar.gz /etc/hostname /etc/os-release. - Inspect it: List the archive contents with
tar -tzf backup.tar.gz. - Unpack it: Extract the archive with
tar -xzf backup.tar.gz.
Pro Tip
Combine your backup script with a cron job (from the previous module) to create automatic nightly backups. Add find /backups -mtime +30 -delete to clean up archives older than 30 days!