BASH

Simple Website Backup Using rsync

Implement a robust bash script to create incremental backups of website files using rsync, ensuring data integrity and efficient storage for disaster recovery.

#!/bin/bash

# Configuration
SOURCE_DIR="/var/www/html"   # Directory to backup
BACKUP_DIR="/mnt/backups/website" # Destination for backups
DATE=$(date +"%Y%m%d_%H%M%S")
LOG_FILE="$BACKUP_DIR/backup_$DATE.log"

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

echo "Starting website backup from $SOURCE_DIR to $BACKUP_DIR..." | tee -a "$LOG_FILE"

# Use rsync for efficient backup
# -a: archive mode (preserves permissions, timestamps, etc.)
# -v: verbose
# --delete: delete extraneous files from dest (if you want an exact mirror)
# --exclude: exclude specific files/directories (e.g., node_modules, .git)
rsync -avz --exclude 'node_modules/' --exclude '.git/' "$SOURCE_DIR/" "$BACKUP_DIR/current_snapshot/" >> "$LOG_FILE" 2>&1

if [ $? -eq 0 ]; then
  echo "Backup completed successfully." | tee -a "$LOG_FILE"
else
  echo "Backup failed!" | tee -a "$LOG_FILE"
fi

# Optional: Clean up old snapshots (e.g., keep last 5)
# find "$BACKUP_DIR" -maxdepth 1 -type d -name "current_snapshot*" -mtime +30 -exec rm -rf {} \;
How it works: This script provides a simple yet powerful way to back up website files using 'rsync'. It defines source and backup directories, creates a timestamped log file, and then uses 'rsync' in archive mode ('-a') to synchronize files. The '--delete' flag (commented out as an option) ensures the destination is an exact mirror, and '--exclude' helps skip unnecessary directories like 'node_modules' or '.git'. This is crucial for disaster recovery.

Need help integrating this into your project?

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

Hire DigitalCodeLabs