Day 9: Shell Scripting Challenge - Directory Backup with Rotation

Ensuring the availability of your crucial work directory is essential in any development environment. Today, I took another step in mastering shell scripting as part of my 90-day DevOps challenge. I practiced a Bash script that automates the backup process with a five-day rotation. This ensures that I always have recent backups without cluttering my storage.
#!/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:
SOURCEis the directory to be backed up.TIME_STAMPcreates a unique identifier for each backup based on the current date and time.DESTis the destination directory for storing backups.
Creating Backups:
The
create_backupfunction compresses theSOURCEdirectory 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_backupfunction 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.
Stay tuned for more updates on my 90-day DevOps journey!