BASH

Backup a Directory with Timestamp and Cleanup Old Backups

Create timestamped tar.gz backups of a directory and automatically delete backups older than a configurable number of days, saving disk space.

#!/bin/bash

SOURCE_DIR="/var/www/mywebapp"
BACKUP_DIR="/var/backups/mywebapp"
DAYS_TO_KEEP=7

TIMESTAMP=$(date +%Y%m%d%H%M%S)
BACKUP_FILE="$BACKUP_DIR/mywebapp_backup_$TIMESTAMP.tar.gz"

mkdir -p "$BACKUP_DIR"

echo "Creating backup of $SOURCE_DIR to $BACKUP_FILE..."
tar -czf "$BACKUP_FILE" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

if [ $? -eq 0 ]; then
    echo "Backup successful."
else
    echo "Backup failed!"
    exit 1
fi


echo "Cleaning up old backups (older than $DAYS_TO_KEEP days)..."
find "$BACKUP_DIR" -type f -name "mywebapp_backup_*.tar.gz" -mtime +$DAYS_TO_KEEP -delete

echo "Cleanup complete."
How it works: This script efficiently backs up a specified source directory by creating a compressed `tar.gz` archive. Each backup file is uniquely named with a timestamp. After creation, the script intelligently cleans up the backup directory by removing any archived files that are older than a user-defined number of days, helping to manage disk space and maintain a history of backups without manual intervention.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs