← Back to all snippets
BASH

Simple Website and Database Backup Script

Create a robust bash script for scheduled backups of your website files and MySQL or PostgreSQL databases, ensuring data safety and quick recovery.

#!/bin/bash

# --- Configuration Start ---
BACKUP_DIR="/var/backups/website"
WEBSITE_ROOT="/var/www/html/your_site"
DB_NAME="your_database_name"
DB_USER="your_database_user"
DB_PASSWORD="your_database_password" # Consider using .my.cnf or environment variables for production
DB_TYPE="mysql" # or "postgresql"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
WEBSITE_ARCHIVE="$BACKUP_DIR/website_backup_$TIMESTAMP.tar.gz"
DB_ARCHIVE="$BACKUP_DIR/database_backup_$TIMESTAMP.sql"
LOG_FILE="$BACKUP_DIR/backup_log.log"
RETENTION_DAYS=7 # Number of days to keep backups
# --- Configuration End ---

mkdir -p "$BACKUP_DIR"
exec > >(tee -a "$LOG_FILE") 2>&1 # Redirect all output to log file and stdout

echo "--- Starting backup at $TIMESTAMP ---"

# 1. Backup Website Files
echo "Backing up website files from $WEBSITE_ROOT..."
tar -czf "$WEBSITE_ARCHIVE" -C "$(dirname "$WEBSITE_ROOT")" "$(basename "$WEBSITE_ROOT")"
if [ $? -eq 0 ]; then
  echo "Website files backup successful: $WEBSITE_ARCHIVE"
else
  echo "Website files backup FAILED!"
fi

# 2. Backup Database
echo "Backing up database '$DB_NAME' ($DB_TYPE)..."
if [ "$DB_TYPE" == "mysql" ]; then
  mysqldump -u"$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" > "$DB_ARCHIVE"
elif [ "$DB_TYPE" == "postgresql" ]; then
  PGPASSWORD="$DB_PASSWORD" pg_dump -U "$DB_USER" "$DB_NAME" > "$DB_ARCHIVE"
else
  echo "Unsupported database type: $DB_TYPE. Skipping database backup."
fi

if [ $? -eq 0 ]; then
  echo "Database backup successful: $DB_ARCHIVE"
else
  echo "Database backup FAILED!"
fi

# 3. Clean up old backups
echo "Cleaning up old backups (older than $RETENTION_DAYS days)..."
find "$BACKUP_DIR" -type f -name "website_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete
find "$BACKUP_DIR" -type f -name "database_backup_*.sql" -mtime +$RETENTION_DAYS -delete
echo "Cleanup complete."

echo "--- Backup finished ---"
How it works: This comprehensive script performs backups of both website files and a specified database (MySQL or PostgreSQL). It creates a timestamped archive of the website's root directory using `tar` and a dump of the database using `mysqldump` or `pg_dump`. All output is logged, and older backups are automatically pruned based on a configurable retention period. This script is ideal for scheduling with `cron` to ensure regular, automated data protection.

Need help integrating this into your project?

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

Hire DigitalCodeLabs