DEV Community

Cover image for BashBlaze Day 2: Directory Backup with Rotation (Part-2)
Muhammad Hanzala Ali
Muhammad Hanzala Ali

Posted on

1

BashBlaze Day 2: Directory Backup with Rotation (Part-2)

Introduction

Welcome back to Day 2 of the BashBlaze - 7 Days of Bash Scripting Challenge!
For this challenge, we’ll create a bash script to automate directory backups with rotation, ensuring that only the most recent versions are stored. This is especially useful in real-world scenarios where storage space matters, and we need to manage backup files efficiently.

Challenge Description

Our goal is to:

  1. Create a bash script that accepts a directory path as a command-line argument.
  2. Generate timestamped backups for the specified directory.
  3. Implement a rotation mechanism to keep only the last three backups, removing the oldest ones automatically.

The script will backup all files in the specified directory and ensure we retain only the three latest backups by removing older ones, keeping our backup folder clutter-free and manageable.

Solution Code

Here’s the bash script that accomplishes our goal:

#!/bin/bash

<<note
This script creates a timestamped backup with rotation, keeping only the last 3 backups.

Usage:
./backup_with_rotation.sh <source_directory> <backup_directory>
note

# Function to display usage information
function display_usage {
    echo "Usage: ./backup_with_rotation.sh <source_directory> <backup_directory>"
}

# Validate command-line arguments
if [ $# -ne 2 ] || [ ! -d "$1" ]; then
    echo "Error: Please provide a valid source directory path and a backup directory."
    display_usage
    exit 1
fi

# Define source and backup directories
source_dir=$1
backup_dir=$2
timestamp=$(date '+%Y-%m-%d-%H-%M-%S')

# Function to create a timestamped backup
function create_backup {
    zip -r "${backup_dir}/backup_${timestamp}.zip" "${source_dir}" > /dev/null
    if [ $? -eq 0 ]; then
        echo "Backup created successfully: ${backup_dir}/backup_${timestamp}.zip"
    fi
}

# Function to keep only the last 3 backups
function perform_rotation {
    # List backups in reverse chronological order
    backups=($(ls -t "${backup_dir}/backup_"*.zip 2>/dev/null))

    # If there are more than 3 backups, delete the oldest ones
    if [ "${#backups[@]}" -gt 3 ]; then
        echo "Performing rotation to keep only the last 3 backups..."
        backups_to_remove=("${backups[@]:3}")
        for backup in "${backups_to_remove[@]}"; do
            rm -f "${backup}"
            echo "Removed old backup: $backup"
        done
    fi
}

# Main script execution
create_backup
perform_rotation

Enter fullscreen mode Exit fullscreen mode

How It Works

Here’s a breakdown of the main components of the script:

  • ## Usage Information:

The script begins by providing a usage note to guide users on the command format.

  • ## Command-Line Argument Validation:

Ensures that both source and backup directories are provided.
Displays an error message if the arguments are missing or invalid.

  • ## Timestamped Backup Creation:

Uses the create_backup function to generate a compressed .zip backup of the source directory.
Names the backup using the current timestamp for easy tracking.

  • ## Backup Rotation:

The perform_rotation function checks if there are more than three backups.

If so, it removes the oldest backups, keeping only the latest three, thus saving space and maintaining recent copies.

Example Usage

Here’s what the script looks like in action:

First Execution

$ ./backup_with_rotation.sh /home/user/documents /home/user/backups
Output:
Backup created successfully: /home/user/backups/backup_2023-07-30_12-30-45.zip

Enter fullscreen mode Exit fullscreen mode

Second Execution with Rotation

When there are more than three backups, the oldest one is removed automatically:

$ ./backup_with_rotation.sh /home/user/documents /home/user/backups
Output:
Backup created successfully: /home/user/backups/backup_2023-08-01_09-15-30.zip
Performing rotation to keep only the last 3 backups...
Removed old backup: /home/user/backups/backup_2023-07-30_12-30-45.zip

Enter fullscreen mode Exit fullscreen mode

Conclusion

Today’s script covers essential automation for backup management with a focus on storage efficiency. By using rotation to retain only the most recent backups, this solution is practical and scalable, especially for servers and personal systems that require regular backups.

Submission Instructions

Push your backup_with_rotation.sh script to your GitHub repository and share your progress with the community! Looking forward to hearing about your experience and any creative ways you apply this script!

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay