BASH

Automating Website & Database Backups

Create a robust Bash script to automate daily backups of your website files and MySQL/PostgreSQL databases, ensuring data safety and easy recovery.

#!/bin/bash
# Configuration
WEB_ROOT="/var/www/mywebsite"
DB_NAME="my_database"
DB_USER="db_user"
DB_PASS="db_password" # Consider using .my.cnf for security
BACKUP_DIR="/backups/mywebsite"
TIMESTAMP=$(date +%Y%m%d%H%M%S)
RETENTION_DAYS=7 # Keep backups for 7 days

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

# 1. Backup Website Files
echo "Backing up website files..."
tar -czf "$BACKUP_DIR/website_files_${TIMESTAMP}.tar.gz" -C "$(dirname "$WEB_ROOT")" "$(basename "$WEB_ROOT")"
if [ $? -eq 0 ]; then
    echo "Website files backup successful."
else
    echo "ERROR: Website files backup failed."
fi

# 2. Backup Database (MySQL example)
echo "Backing up database..."
mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" > "$BACKUP_DIR/database_${TIMESTAMP}.sql"
# For PostgreSQL: pg_dump -U "$DB_USER" "$DB_NAME" > "$BACKUP_DIR/database_${TIMESTAMP}.sql"
if [ $? -eq 0 ]; then
    echo "Database backup successful."
else
    echo "ERROR: Database backup failed."
fi

# 3. Clean up old backups
echo "Cleaning up old backups (older than $RETENTION_DAYS days)..."
find "$BACKUP_DIR" -type f -mtime +$RETENTION_DAYS -delete
echo "Backup script finished."
How it works: This script automates creating compressed archives of website files and database dumps. It uses `tar` for files and `mysqldump` (or `pg_dump` for PostgreSQL) for databases. It also includes a cleanup mechanism to remove backups older than a specified number of days, helping manage disk space.

Need help integrating this into your project?

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

Hire DigitalCodeLabs