BASH

Automate Website & Database Backups

Learn to create a robust Bash script for automating website files and MySQL/PostgreSQL database backups, complete with timestamped archives and cleanup.

#!/bin/bash

# Configuration
BACKUP_DIR="/var/backups/mywebsite"
WEBSITE_ROOT="/var/www/mywebsite"
DB_USER="db_username"
DB_PASS="db_password"
DB_NAME="my_database"

TIMESTAMP=$(date +%Y%m%d%H%M%S)

mkdir -p "$BACKUP_DIR"

# Backup website files
tar -czf "$BACKUP_DIR/website_backup_$TIMESTAMP.tar.gz" -C "$WEBSITE_ROOT" .

# Backup database (MySQL example)
mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_DIR/database_backup_$TIMESTAMP.sql.gz"

# Alternative for PostgreSQL:
# pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_DIR/database_backup_$TIMESTAMP.sql.gz"

# Clean up old backups (e.g., keep last 7 days)
find "$BACKUP_DIR" -type f -name "*.tar.gz" -mtime +7 -delete
find "$BACKUP_DIR" -type f -name "*.sql.gz" -mtime +7 -delete

echo "Backup completed: $TIMESTAMP"
How it works: This script automates backups of a website's files and its associated MySQL (or PostgreSQL) database. It creates a timestamped `tar.gz` archive of the website's document root and a `gzip`-compressed SQL dump of the database. Finally, it prunes old backups older than 7 days, ensuring disk space is managed. This script is ideal for scheduling with cron jobs for routine backups.

Need help integrating this into your project?

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

Hire DigitalCodeLabs