Skip to content

DAY-1 Solution by Shina Gupta #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions Challenges/Day_2/backup_with_rotation.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/bin/bash

# Function to display usage information and available options
# Display usage information
function display_usage {
echo "Usage: $0 /path/to/source_directory"
}
Expand All @@ -12,27 +12,32 @@ if [ $# -eq 0 ] || [ ! -d "$1" ]; then
exit 1
fi

# Directory path of the source directory to be backed up
# Assign source directory from command-line argument
source_dir="$1"

# Function to create a timestamped backup folder
# Function to create a timestamped backup and zip it
function create_backup {
local timestamp=$(date '+%Y-%m-%d_%H-%M-%S') # Get the current timestamp
local timestamp=$(date '+%Y-%m-%d_%H-%M-%S')
local backup_dir="${source_dir}/backup_${timestamp}"

# Create the backup folder with the timestamped name
mkdir "$backup_dir"
echo "Backup created successfully: $backup_dir"
# Create backup directory and zip its contents
zip -r "${backup_dir}.zip" "$source_dir" >/dev/null
if [ $? -eq 0 ]; then
echo "Backup created successfully: ${backup_dir}.zip"
else
echo "Error: Failed to create backup."
fi
}

# Function to perform the rotation and keep only the last 3 backups
# Function to perform rotation and keep only the last 3 backups
function perform_rotation {
local backups=($(ls -t "${source_dir}/backup_"* 2>/dev/null)) # List existing backups sorted by timestamp
local backups=($(ls -t "${source_dir}/backup_"*.zip 2>/dev/null))

# Check if there are more than 3 backups
if [ "${#backups[@]}" -gt 3 ]; then
local backups_to_remove="${backups[@]:3}" # Get backups beyond the last 3
rm -rf "${backups_to_remove[@]}" # Remove the oldest backups
local backups_to_remove=("${backups[@]:3}")
for backup in "${backups_to_remove[@]}"; do
rm -f "$backup"
done
fi
}

Expand Down