#90DaysOfDevops | Day 9
Day 9 -> Shell Scripting Challenge Directory Backup with Rotation
Challenge Description
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.
The Script
Below is the Bash script named backup_with_
rotation.sh
that implements the described functionality:
#!/bin/bash
<< comment
This script is for backup of the work_dir with 5 day rotation
comment
SOURCE="/home/ubuntu/work_dir"
TIME_STAMP=$(date +%Y_%m_%H_%M%S)
DEST="/home/ubuntu/backup"
# Function to create backup
function create_backup {
zip -r "$DEST/backupfile_${TIME_STAMP}.zip" "$SOURCE" >/dev/null
if [ $? -eq 0 ]; then
echo "Backup generated successfully for $TIME_STAMP"
fi
}
# Function to remove old backups beyond the 5-day rotation
function rotation_backup {
backups=($(ls -t "$DEST/backup"*zip))
backups_to_remove=("${backups[@]:5}")
for i in "${backups_to_remove[@]}"; do
rm -rf $i
done
}
# Main execution
create_backup
rotation_backup
How It Works:
Defining Variables:
SOURCE
is the directory to be backed up.TIME_STAMP
creates a unique identifier for each backup based on the current date and time.DEST
is the destination directory for storing backups.
Creating Backups:
The
create_backup
function compresses theSOURCE
directory into a zip file named with the current timestamp.It verifies if the backup is successfully created and provides feedback.
Managing Backup Rotation:
The
rotation_backup
function lists the existing backups sorted by modification time.It then removes backups older than the most recent five, maintaining a five-day rotation.
Backup Rotation: The script rotates the last five backups, automatically removing the oldest ones to manage storage space efficiently.
By automating this process, I ensure that my work is consistently backed up without manual intervention, and old backups are pruned regularly to avoid consuming unnecessary storage.
Happy Learning ๐