diff --git a/Challenges/Day_2/backup_with_rotation.sh b/Challenges/Day_2/backup_with_rotation.sh index 2c5e56f6..5e60060e 100644 --- a/Challenges/Day_2/backup_with_rotation.sh +++ b/Challenges/Day_2/backup_with_rotation.sh @@ -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" } @@ -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 }