DEV Community

Kanav Gathe
Kanav Gathe

Posted on

Day 9/90: Directory Backup with Rotation in Shell Scripting πŸ”„ #90DaysOfDevOps

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
Enter fullscreen mode Exit fullscreen mode

Script Features πŸ”§

  1. Input Validation

    • Checks for correct usage
    • Verifies directory existence
  2. Backup Creation

    • Timestamped backups
    • Complete directory copying
    • Error handling
  3. Rotation Mechanism

    • Maintains last 3 backups
    • Automatically removes old backups
    • Sorted by timestamp
  4. 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
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)