BASH

Automate Full Website Backups (Files & DB)

Create a robust bash script to automate daily backups of your web application's files and MySQL/PostgreSQL database, storing them with timestamps for recovery.

#!/bin/bash

# Configuration Variables
BACKUP_DIR="/path/to/your/backups"
WEB_ROOT="/var/www/your_website"
DB_USER="your_db_user"
DB_PASS="your_db_password"
DB_NAME="your_database_name"
DB_TYPE="mysql" # or "postgresql"
RETENTION_DAYS=7 # Number of days to keep backups

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

# Generate timestamp for backup files
TIMESTAMP=$(date +%Y%m%d%H%M%S)
BACKUP_PATH="$BACKUP_DIR/$TIMESTAMP"
mkdir -p "$BACKUP_PATH"

echo "Starting backup at $TIMESTAMP..."

# 1. Backup Website Files
echo "Backing up website files from $WEB_ROOT..."
tar -czf "$BACKUP_PATH/website_files.tar.gz" -C "$WEB_ROOT" .
if [ $? -eq 0 ]; then
    echo "Website files backup complete."
else
    echo "ERROR: 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_PASS" "$DB_NAME" | gzip > "$BACKUP_PATH/database.sql.gz"
elif [ "$DB_TYPE" == "postgresql" ]; then
    PGPASSWORD="$DB_PASS" pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_PATH/database.sql.gz"
else
    echo "ERROR: Unsupported database type: $DB_TYPE"
fi

if [ $? -eq 0 ]; then
    echo "Database backup complete."
else
    echo "ERROR: Database backup failed!"
fi

echo "Backup stored in: $BACKUP_PATH"

# 3. Clean up old backups
echo "Cleaning up backups older than $RETENTION_DAYS days..."
find "$BACKUP_DIR" -maxdepth 1 -type d -mtime +$RETENTION_DAYS -exec rm -rf {} \;

echo "Backup process finished."
How it works: This bash script provides a comprehensive solution for automating website backups. It first defines configurable variables for paths, database credentials, and retention policy. It creates a timestamped directory for each backup, then uses `tar -czf` to compress and archive the website's files. For the database, it uses `mysqldump` (for MySQL) or `pg_dump` (for PostgreSQL), piping the output directly to `gzip` for compression. Finally, it uses `find` to locate and delete backup directories older than the specified `RETENTION_DAYS`, ensuring disk space is managed. This script can be scheduled via cron for daily execution.

Need help integrating this into your project?

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

Hire DigitalCodeLabs