Day 2 - Part II: Directory Backup with Rotation using BashπŸ“‚

Day 2 - Part II: Directory Backup with Rotation using BashπŸ“‚

πŸ“ Introduction:

Welcome to Day 2 of the #TWSBashBlazeChallenge! Today's challenge focuses on creating a powerful Bash script to protect your important files by performing directory backups with rotation capabilities. πŸ›‘οΈ Data loss can be devastating, and having a robust backup strategy is crucial in ensuring the safety of your valuable information. We'll build a script named backup_with_rotation.sh that automates the process of creating timestamped backups and retaining only the last 3 backups, allowing you to safeguard your files effectively. Let's dive into the world of Bash scripting and backup magic! 🌟

Why Directory Backup with Rotation is Crucial? πŸ”‘πŸ”„

Regular backups are essential to safeguard your files from data loss caused by various factors such as hardware failures, accidental deletions, malware attacks, and more. When you create multiple backups, you increase the chances of recovering your data even if one backup becomes corrupted or outdated. However, managing multiple backups can be challenging and may consume significant disk space over time.

This is where directory backup with rotation comes to the rescue! The rotation mechanism allows you to keep only the most recent backups (e.g., the last 3 backups) and automatically removes older backups. This approach strikes a balance between data protection and storage efficiency, ensuring you have access to the most recent backups while optimizing disk space. With our backup_with_rotation.sh script, you can effortlessly maintain a robust backup routine and protect your files like a pro! 🌈

Let's Get Started with the Script! πŸš€

We'll now dive into the implementation of our backup_with_rotation.sh script. The script takes a directory path as a command-line argument and performs a backup of the specified directory. Let's go step by step and understand each part of the script.

πŸ” Check for the argument provided or not:

#!/bin/bash

# Check if a directory path is provided as a command-line argument
if [[ $# -ne 1 ]]; then
    echo "Usage: $0 <directory_path>"
    exit 1
fi

# Get the specified directory path from the command-line argument
directory_path="$1"

πŸ” Part 1: Creating Timestamped Backup Folder and Copying Files

To initiate the backup process, we need to create a timestamped backup folder inside the specified directory and copy all the files into it.

# Function to create a timestamped backup folder
create_backup_folder() {
    local timestamp=$(date +'%Y-%m-%d_%H-%M-%S')
    local backup_folder="${directory_path}/backup_${timestamp}"
    mkdir "$backup_folder"
    echo "$backup_folder"
}

# Create the backup folder
backup_folder=$(create_backup_folder)

# Copy all files from the specified directory to the backup folder
cp -R "$directory_path"/* "$backup_folder"

echo "Backup created: $backup_folder"

We use the create_backup_folder function to generate a timestamp with the current date and time in the format YYYY-MM-DD_HH-MM-SS. We then create a folder named backup_YYYY-MM-DD_HH-MM-SS inside the specified directory. Next, we use the cp command to recursively copy all the files from the source directory to the backup folder.

πŸ’‘ Part 2: Rotation Mechanism - Managing Only the Last 3 Backups

Now comes the crucial part! We want to ensure that only the last 3 backups are retained, removing any older backups if they exist.

# Function to remove the oldest backup folders if more than 3 backups exist
remove_old_backups() {
    local backup_folders=("$directory_path"/backup_*)
    local num_backups="${#backup_folders[@]}"

    # Check if the number of backups is greater than 3
    if [[ $num_backups -gt 3 ]]; then
        # Sort the backup folders based on their creation time (oldest first)
        # and remove the excess ones (leaving the last 3 backups)
        sorted_backups=($(printf '%s\n' "${backup_folders[@]}" | sort))
        backups_to_remove=("${sorted_backups[@]:0:$((num_backups-3))}")

        for backup_to_remove in "${backups_to_remove[@]}"; do
            echo "Removing old backup: $backup_to_remove"
            rm -rf "$backup_to_remove"
        done
    fi
}

# Part 2: Remove the oldest backups to keep only the last 3 backups

remove_old_backups

The remove_old_backups function identifies all the existing backup folders and counts the total number of backups. If there are more than 3 backups, it sorts the backup folders based on their creation time and removes the excess ones, retaining only the last 3 backups.

πŸ“œ All in one - backup_with_rotation.sh

#!/bin/bash

# Check if a directory path is provided as a command-line argument
if [[ $# -ne 1 ]]; then
    echo "Usage: $0 <directory_path>"
    exit 1
fi

# Get the specified directory path from the command-line argument
directory_path="$1"

# Function to create a timestamped backup folder
create_backup_folder() {
    local timestamp=$(date +'%Y-%m-%d_%H-%M-%S')
    local backup_folder="${directory_path}/backup_${timestamp}"
    mkdir "$backup_folder"
    echo "$backup_folder"
}

# Function to remove the oldest backup folders if more than 3 backups exist
remove_old_backups() {
    local backup_folders=("$directory_path"/backup_*)
    local num_backups="${#backup_folders[@]}"

    # Check if the number of backups is greater than 3
    if [[ $num_backups -gt 3 ]]; then
        # Sort the backup folders based on their creation time (oldest first)
        # and remove the excess ones (leaving the last 3 backups)
        sorted_backups=($(printf '%s\n' "${backup_folders[@]}" | sort))
        backups_to_remove=("${sorted_backups[@]:0:$((num_backups-3))}")

        for backup_to_remove in "${backups_to_remove[@]}"; do
            echo "Removing old backup: $backup_to_remove"
            rm -rf "$backup_to_remove"
        done
    fi
}

# Part 1: Create timestamped backup folder and copy all files into it

# Create the backup folder
backup_folder=$(create_backup_folder)

# Copy all files from the specified directory to the backup folder
cp -R "$directory_path"/* "$backup_folder"

echo "Backup created: $backup_folder"

# Part 2: Remove the oldest backups to keep only the last 3 backups

remove_old_backups

# End of script

πŸ” Output Screen:

⚜ Image Credit:

Make an Incremental Backup Script with Bash!

πŸ“ Conclusion πŸŽ‰

Congratulations! You have successfully built a powerful Bash script named backup_with_rotation.sh that performs directory backups with rotation capabilities. By creating timestamped backups and managing only the last 3 backups, you have implemented an efficient backup strategy to protect your files from unexpected data loss. πŸ’ͺπŸ“¦

Remember, maintaining regular backups is essential for the safety of your data, and rotation ensures that you strike a perfect balance between data protection and storage efficiency. With this script, you are now equipped to safeguard your important files like a pro! πŸ›‘οΈπŸ’Ύ Stay tuned for more exciting challenges in the #TWSBashBlazeChallenge! Keep exploring and expanding your Bash scripting skills. Until then, happy coding! πŸŒŸπŸŽ‰

πŸ” Checkout GitHub Repository for projects:

πŸ”— github.com/sumanprasad007

πŸ” Check out my YouTube channel - Prasad Suman Mohan:

πŸ”— youtube.com/@sumanprasad007

Did you find this article valuable?

Support Prasad Suman Mohan by becoming a sponsor. Any amount is appreciated!

Β