BASH
Automating Website File Backups to a Remote Server
Learn to create a robust bash script for automating website file synchronization, securely updating directories on a remote server using rsync for efficient backups.
#!/bin/bash
# Configuration
LOCAL_WEB_ROOT="/var/www/html" # Directory to backup
REMOTE_USER="your_ssh_user"
REMOTE_HOST="your_remote_server.com"
REMOTE_PATH="/path/to/remote/backups" # Path on remote server
# Ensure the remote path exists (requires passwordless SSH or password prompt)
ssh "$REMOTE_USER@$REMOTE_HOST" "mkdir -p $REMOTE_PATH" || { echo "Error: Could not connect to remote host or create remote path!"; exit 1; }
echo "Starting website file synchronization to $REMOTE_HOST:$REMOTE_PATH..."
# Use rsync to synchronize files.
# -a: archive mode (preserves permissions, timestamps, etc.)
# -v: verbose
# -z: compress file data during the transfer
# --delete: delete extraneous files from dest (if not in source)
# --exclude: exclude specific files/directories (e.g., node_modules, .git)
rsync -avz --delete \
--exclude 'node_modules/' \
--exclude '.git/' \
--exclude 'tmp/' \
"$LOCAL_WEB_ROOT/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/current_website_sync" || { echo "Rsync failed!"; exit 1; }
# Optional: Backup a database (simulated, needs actual db dump command, e.g., mysqldump)
# echo "Performing database backup (if applicable)..."
# mysqldump -u DB_USER -pDB_PASSWORD DBNAME > /tmp/db_backup.sql
# scp /tmp/db_backup.sql "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/db_backup_$(date +%Y%m%d_%H%M%S).sql"
# rm /tmp/db_backup.sql
echo "Website file synchronization completed successfully."
How it works: This script uses `rsync` to efficiently synchronize a local website directory to a remote server. `rsync -avz --delete` ensures an archive mode transfer, compresses data, and mirrors deletions, making it ideal for incremental backups. It includes common exclusions like `node_modules` and `.git` directories, and provides basic error handling for connection and transfer failures. It can be extended for database backups using tools like `mysqldump`.