BASH

Create and Rotate Directory Backups

Automate daily or weekly backups of a specified directory using tar and gzip. Implement a smart rotation strategy to keep only a set number of recent backups.

#!/bin/bash

BACKUP_DIR="/var/backups/web_data/"
SOURCE_DIR="/var/www/html/"
RETENTION_DAYS=7

mkdir -p "$BACKUP_DIR"

TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}web_data_backup_${TIMESTAMP}.tar.gz"

echo "Creating backup of $SOURCE_DIR to $BACKUP_FILE..."
tar -czf "$BACKUP_FILE" "$SOURCE_DIR"

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

echo "Rotating old backups (keeping last $RETENTION_DAYS days)..."
find "$BACKUP_DIR" -type f -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete

echo "Backup script finished."
How it works: This script creates a compressed tar archive of a specified source directory and stores it in a timestamped file within a backup directory. After creating the backup, it then efficiently rotates old backups by deleting any backup files older than a specified number of `RETENTION_DAYS`, managing storage space.

Need help integrating this into your project?

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

Hire DigitalCodeLabs