BASH

Automate Full Website and Database Backups

Automate full website backups, including files and MySQL database, with timestamped archives for easy restoration and disaster recovery.

#!/bin/bash

# Configuration
WEB_ROOT="/var/www/html" # Path to your website's root directory
DB_NAME="your_database_name"
DB_USER="your_database_user"
DB_PASS="your_database_password"
BACKUP_DIR="/opt/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/website_backup_${TIMESTAMP}.tar.gz"
DB_BACKUP_FILE="${BACKUP_DIR}/database_backup_${TIMESTAMP}.sql"

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

echo "Starting website backup..."

# Backup database
echo "Backing up database: ${DB_NAME}..."
mysqldump -u"${DB_USER}" -p"${DB_PASS}" "${DB_NAME}" > "${DB_BACKUP_FILE}"
if [ $? -eq 0 ]; then
  echo "Database backup successful: ${DB_BACKUP_FILE}"
else
  echo "Error: Database backup failed."
  exit 1
fi

# Backup website files
echo "Backing up website files from: ${WEB_ROOT}..."
tar -czf "${BACKUP_FILE}" -C "$(dirname "${WEB_ROOT}")" "$(basename "${WEB_ROOT}")"
if [ $? -eq 0 ]; then
  echo "Website files backup successful: ${BACKUP_FILE}"
else
  echo "Error: Website files backup failed."
  exit 1
fi

echo "Backup complete!"
How it works: This script automates backing up a website's files and a MySQL database. It creates a timestamped tarball of the web root and a SQL dump of the specified database, storing them in a designated backup directory. It includes basic error checking for the backup operations. Remember to replace placeholder values with your actual configuration.

Need help integrating this into your project?

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

Hire DigitalCodeLabs