Day 9 Task: Shell Scripting Challenge Directory Backup with Rotation

Day 9 Task: Shell Scripting Challenge Directory Backup with Rotation

Directory Backup Rotation Task

Your 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.

Rotation Scripts:

#!/bin/bash 

SOURCE_DIR=$1

BACKUP_DIR=$2

TIMESTAMP=$(date +%Y%m%d%H%M%S)

if [ ! -d "$SOURCE_DIR" ]; then

        echo "Error: ${SOURCE_DIR} doesn't exist" 
        exit 1
fi


tar -czvf "${BACKUP_DIR}/shell_task${TIMESTAMP}.tar.gz" "${SOURCE_DIR}"

if [ $? -eq 0 ]; then
        echo "Backup created succesfully" 
else
        echo "Backup hasn't created"
fi

# Correctly handle the output of ls -t as an array

BACKUP_FILES=($(ls -t "${BACKUP_DIR}/shell_task"*.tar.gz))

# Check if there are more than 3 backups

if [ "${#BACKUP_FILES[@]}" -gt 3 ]; then
       for ((i=3; i<${#BACKUP_FILES[@]}; i++)); do  # Loop from the 4th file onward

        rm -rf "${BACKUP_FILES[$i]}"

        echo "Old backup removed: ${BACKUP_FILES[$i]}"
    done
fi

Final Output

As we declared in scripts all backup will be collected in Copy directory and in Output print we got the latest 3 backup in the Copy directory.

Thank You, Please follow me more updates:)