Day 9 Task: Shell Scripting Challenge ๐Ÿš Directory Backup with Rotation ๐Ÿ”„

ยท

3 min read

The task is to create a bash script that takes a directory path as a command-line argument and performs a backup of the directory. The script should create timestamped backup folders and copy all the files from the specified directory into the backup folder.

Additionally, the script should implement a rotation mechanism to keep only the last 3 backups. This means that if there are more than 3 backup folders, the oldest backup folders should be removed to ensure only the most recent backups are retained.

Answer:

This shell script creates a compressed backup of a directory, stores it in a destination folder, and maintains only the 3 most recent backups by deleting older ones (rotation system).

Folders Setup:

  • Source folder: We have created a folder named Data where all the files that need to be backed up are stored.

  • Destination folder: Another folder named Backup is created where all the backup zip files will be stored.

To create these folders, use the following commands:

mkdir Backup

Key Parts:

  1. Usage:

    • The script takes two arguments:

      • Source path: The directory you want to back up.

      • Destination path: Where the backup will be stored.

Example usage:
./backup.sh /path/to/source /path/to/destination

  1. Backup Creation:

    • The create_backup function compresses the source directory (source_dir) into a zip file with a timestamp (backup_YYYY-MM-DD-HH-MM-SS.zip) and saves it to the destination folder (destination_dir).

    • It also checks if the backup was created successfully and prints a success message.

  2. Backup Rotation:

    • The backup_rotation function checks the destination folder for backup files.

    • If more than 3 backups exist, it deletes the oldest ones, retaining only the 3 most recent backups (to save space).

  3. Execution:

    • The script first creates the backup by calling create_backup.

    • Then, it performs the rotation by calling backup_rotation, ensuring no more than 3 backups are retained.

Flow:

  1. Create a backup of the source directory.

  2. Remove older backups if there are more than 3 backups in the destination folder.

  3. Schedule the backup to run automatically every minute using cron.

Below is the complete script code:-

#!/bin/bash
<<readme
This script is for 5 days rotational backups
Usage: ./backup.sh <Source path> <Destination path>
readme
function usage_display {
echo "Usage: ./backup.sh <Source path> <Destination path>"
}
if [ $# -eq 0 ]; then
  usage_display
fi
source_dir=$1
timestamp=$(date '+%Y-%m-%d-%H-%M-%S')
destination_dir=$2
function create_backup {
     zip -r "${destination_dir}/backup_${timestamp}.zip" "${source_dir}" > /dev/null
    if [ $? -eq 0 ]; then
            echo "Backup completed successfully for ${timestamp}"
    fi
}
function backup_rotation {
        backups=($(ls -t "${destination_dir}/backup_"*.zip))
  if [ "${#backups[@]}" -gt 3 ]; then
           echo "Performing rotation for 3 days"
           remove_backups=("${backups[@]:3}")
           for backup in "${remove_backups[@]}";
           do
                   rm -f ${backup}
           done

  fi
}
create_backup
backup_rotation

Scheduling with Cron:

To automate this backup process, we use cron, a time-based job scheduler in Unix-like systems. We can schedule the script to run automatically at specified intervals.

For this task, we set up cron to schedule the backups every minute.

  1. Open the cron editor by running:

     codecrontab -e
    
  2. Add the following line to schedule the script to run every minute:

     * * * * * /path/to/backup.sh /path/to/Data /path/to/Backup
    
    • The * * * * * cron expression represents every minute.

    • Make sure to replace /path/to/backup.sh, /path/to/Data, and /path/to/Backup with the actual paths.

Output:-

Only 3 most recent backups getting stored in the Backup folder by deleting older ones (rotation system).

ย