Day 9: Directory Backup with Rotation 🚀
Hello DevOps enthusiasts! 👋 Welcome to Day 9 of the #90DaysOfDevOps challenge. Today, we're building a backup system with rotation functionality.
Backup Script Solution 💻
#!/bin/bash
# Check if directory argument is provided
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory_path>"
exit 1
fi
# Variables
source_dir="$1"
timestamp=$(date +%Y-%m-%d_%H-%M-%S)
backup_dir="${source_dir}/backup_${timestamp}"
# Check if source directory exists
if [ ! -d "$source_dir" ]; then
echo "Error: Source directory does not exist"
exit 1
fi
# Create backup
echo "Creating backup in $backup_dir"
mkdir -p "$backup_dir"
cp -r "${source_dir}/"* "$backup_dir" 2>/dev/null
# Implement rotation (keep only last 3 backups)
cd "$source_dir"
ls -d backup_* 2>/dev/null | sort | head -n -3 | xargs rm -rf 2>/dev/null
echo "Backup completed. Current backups:"
ls -d backup_* 2>/dev/null
Script Features 🔧
-
Input Validation
- Checks for correct usage
- Verifies directory existence
-
Backup Creation
- Timestamped backups
- Complete directory copying
- Error handling
-
Rotation Mechanism
- Maintains last 3 backups
- Automatically removes old backups
- Sorted by timestamp
-
Status Reports
- Clear error messages
- Completion confirmation
- Lists current backups
Usage Examples 📝
# Create backup
./backup_with_rotation.sh /home/user/documents
# Expected Output:
# Creating backup in /home/user/documents/backup_2024-10-24_14-30-00
# Backup completed. Current backups:
# backup_2024-10-24_12-00-00
# backup_2024-10-24_13-00-00
# backup_2024-10-24_14-30-00
Key Takeaways 💡
- Automated backups ensure data safety
- Rotation prevents disk space issues
- Timestamps enable version tracking
- Error handling is crucial
Bash #DevOps #Automation #Linux #90DaysOfDevOps
This is Day 9 of my #90DaysOfDevOps journey. Keep backing up and rotating!