Skip to main content

Command Palette

Search for a command to run...

Day 9: Shell Scripting Challenge - Directory Backup with Rotation

Published
2 min read
Day 9: Shell Scripting Challenge - Directory Backup with Rotation

Ensuring the availability of your crucial work directory is essential in any development environment. Today, I took another step in mastering shell scripting as part of my 90-day DevOps challenge. I practiced a Bash script that automates the backup process with a five-day rotation. This ensures that I always have recent backups without cluttering my storage.

#!/bin/bash

<< comment
This script is for backup of the work_dir with 5 day rotation
comment

SOURCE="/home/ubuntu/work_dir"
TIME_STAMP=$(date +%Y_%m_%H_%M%S)
DEST="/home/ubuntu/backup"

# Function to create backup
function create_backup {
    zip -r "$DEST/backupfile_${TIME_STAMP}.zip" "$SOURCE" >/dev/null

    if [ $? -eq 0 ]; then
        echo "Backup generated successfully for $TIME_STAMP"
    fi
}

# Function to remove old backups beyond the 5-day rotation
function rotation_backup {
    backups=($(ls -t "$DEST/backup"*zip))
    backups_to_remove=("${backups[@]:5}")

    for i in "${backups_to_remove[@]}"; do
        rm -rf $i
    done
}

# Main execution
create_backup
rotation_backup

How It Works:

  1. Defining Variables:

    • SOURCE is the directory to be backed up.

    • TIME_STAMP creates a unique identifier for each backup based on the current date and time.

    • DEST is the destination directory for storing backups.

  2. Creating Backups:

    • The create_backup function compresses the SOURCE directory into a zip file named with the current timestamp.

    • It verifies if the backup is successfully created and provides feedback.

  3. Managing Backup Rotation:

    • The rotation_backup function lists the existing backups sorted by modification time.

    • It then removes backups older than the most recent five, maintaining a five-day rotation.

Backup Rotation: The script rotates the last five backups, automatically removing the oldest ones to manage storage space efficiently.

By automating this process, I ensure that my work is consistently backed up without manual intervention, and old backups are pruned regularly to avoid consuming unnecessary storage.

Stay tuned for more updates on my 90-day DevOps journey!

More from this blog

#90DaysOfDevOps Challenge - Day 1 Devops

21 posts