Day 9 Task: Shell Scripting Challenge Directory Backup with Rotation

Pakeeza SaeedPakeeza Saeed
1 min read
#!/bin/bash

# A script to create backups and perform rotation on the last 3 backups.

# Check if the directory path is provided as an argument.
if [[ $# -eq 0 ]]; then
    echo "Usage Error: Please provide a valid directory path."
    exit 1
fi

# Create a 'testbackup' directory if it doesn't exist.
mkdir -p testbackup

# Variables for source directory, timestamp, and target backup directory.
source_dir=$1
time_stamp=$(date '+%Y-%m-%d_%H-%M-%S')
tgt_dir="$source_dir/testbackup/backup_$time_stamp.zip"

# Function to create a backup using the zip command.
function create_backup {
    zip -r "$tgt_dir" "$source_dir" > /dev/null  # Suppress output with '>/dev/null'
    if [[ $? -eq 0 ]]; then
        echo "Backup created successfully."
    else
        echo "Error: Failed to create backup."
    fi
}

# Function to perform backup rotation (keep only the last 3 backups).
function perform_rotation {
    # List backups in 'testbackup', sorted by time, and store them in an array.
    backup=($(ls -t $source_dir/testbackup/backup_*.zip))

    # If more than 4 backups exist, delete the oldest ones.
    if [ ${#backup[@]} -gt 4 ]; then
        echo "Performing rotation for backups older than the last 3."
        backups_to_remove=("${backup[@]:4}")  # Array slicing to select backups to delete.
        for b in "${backups_to_remove[@]}"; do
            rm -rf "$b"  # Remove the old backups.
        done
    fi
}

# Call the functions to create a backup and perform rotation.
create_backup
perform_rotation
0
Subscribe to my newsletter

Read articles from Pakeeza Saeed directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pakeeza Saeed
Pakeeza Saeed