Skip to main content

Command Palette

Search for a command to run...

Shell Script for Rotational Backup

Published
5 min read
Shell Script for Rotational Backup

Intro

In this tutorial, we'll walk you through a simple shell script to take rotational backups of a directory. This script ensures you never run out of disk space by keeping only the latest 5 backups and deleting the older ones. Let’s dive in! 💻


What is Rotational Backup?

A rotational backup keeps the latest versions of your data while automatically removing old backups, saving disk space. In this script, we will:

  1. Backup the directory specified by the user.

  2. Rotate the backups by keeping only the most recent 5 and deleting the older ones.


🔧 What Does This Script Do?

  • Takes user input for:

    • Source directory (to back up)

    • Target directory (where backups are stored)

  • Validates if both paths exist

  • Creates a compressed .tgz backup with a timestamp

  • Automatically removes older backups — keeping only the latest 5


📜 complete Script

script: rotational_backup.sh

#!/bin/bash
#########################
# Author: Anju
# Date: 13/4/2025
# version: V1
#Write a shell script to take a rotational backup of a perticular directory
########################################
read -p "Please enter source directory path: " src_dir

#to check if this path exist or not
if [ ! -d "$src_dir" ]; then
        echo "This $src_dir does not exist"
        exit 1
fi

read -p "Please enter Target directory path: " target_dir #where you wants to take backup
if [ ! -d "$target_dir" ]; then
        echo "This $target_dir does not exist"
        exit 1
fi

curr_time_stamp=$(date +%Y-%m-%d-%H-%M-%S) #this is just for current time
backup_file=$target_dir/$curr_time_stamp.tgz #this will decide the path and name of backup file
#function defination
function backup_script {
   tar czf "$backup_file" "$src_dir"
   if [ $? -eq 0 ]; then
        echo "Backup taken successfully at $curr_time_stamp ."
   else
        echo "error: Try again to take backup"
   fi
}
function perform_rotation {
     backup=($(ls -t "$target_dir"/*tgz))
     if [ "${#backup[@]}" -gt 5 ]; then
           echo "performing rotation for 5 backups files"
           backupFiles_to_delete=("${backup[@]:5}")
           for file in "${backupFiles_to_delete[@]}"; do
              rm -rf "$file"
              echo "Deleted old backup: $file"
           done
      fi
}
  • How to Run the Script:

    1. Make the script executable:

       chmod +x rotational_backup.sh
      
    2. Run the script:

       ./rotational_backup.sh
      

You’ll be prompted to input the source and target directories, and the script will take care of the rest — backing up the source and rotating the backups automatically!

After creating 6 backups, we will check the target directory to see if the backup files are present. We will also verify if running this script more than 6 times results in rotational backups.

🧠 Understanding the Script (Step-by-Step)

✅ 1. Taking Directory Input

We start by taking input for the source directory (the one to be backed up) and the target directory (where backups will be stored).

read -p "Please enter source directory path: " src_dir
read -p "Please enter target directory path: " target_dir

We ask the user where the source and target directories are.


✅ 2. Validating Paths

if [ ! -d "$src_dir" ]; then
    echo "This $src_dir does not exist"
    exit 1
fi

Here, we check if both directories exist. If any directory doesn’t exist, the script exits early with an error message.


✅ 3. Creating a Timestamped Backup File

Next, we create a backup of the source directory using the tar command. The backup will be named with the current timestamp for easy tracking

curr_time_stamp=$(date +%Y-%m-%d-%H-%M-%S)
backup_file=$target_dir/$curr_time_stamp.tgz

We use date to generate a unique name for the backup file, like:
2025-04-13-14-10-57.tgz

This ensures that every backup has a clear, sortable name.


✅ 4. Creating the Backup

Now we define the function to actually create the backup using tar. It’s a compressed .tgz file, which reduces storage space.

function backup_script {
    tar czf "$backup_file" "$src_dir"
    if [ $? -eq 0 ]; then
        echo "Backup taken successfully at $curr_time_stamp."
    else
        echo "Error: Try again to take backup"
    fi
}

The tar command compresses the source folder into .tgz.
c = create
z = gzip
f = filename

You might see:

tar: Removing leading '/' from member names

No worries! That just means it’s removing the / from absolute paths (a safety feature).


✅ 5. Backup Rotation Logic

We need to delete old backups to maintain only the latest 5 backups. This is where the rotation logic comes into play.

Here's how it works:

  1. List backups: We get all .tgz files sorted by time (most recent first).

  2. Count backups: If there are more than 5 backups, we need to delete the oldest ones.

  3. Delete excess backups: We remove all backups that are older than the latest 5.

bashCopyEditfunction perform_rotation {
    backup=($(ls -t "$target_dir"/*tgz))

    if [ "${#backup[@]}" -gt 5 ]; then
        echo "Performing rotation for 5 backup files"
        backupFiles_to_delete=("${backup[@]:5}")

        for file in "${backupFiles_to_delete[@]}"; do
            rm -rf "$file"
            echo "Deleted old backup: $file"
        done
    fi
}

Explanation:

  1. backup=($(ls -t "$target_dir"/*tgz)): List and sort all .tgz files in the target directory.

  2. if [ "${#backup[@]}" -gt 5 ]; then: If there are more than 5 backups, we proceed with rotation.

  3. ${#array[@]} gives you the length of the array — that’s what you want to compare

  4. backupFiles_to_delete=("${backup[@]:5}"): Select backups to delete (those beyond index 5).

  5. rm -rf "$file": Delete each old backup.

This ensures that only 5 most recent backups are kept.

Hope this helps! 🚀

More from this blog

DevOps journey

34 posts

In this DevOps journey, we’ll explore a range of DevOps tools and related projects.