BASH
Simple Website Backup to Local/Remote
Create compressed backups of website files, storing them locally or transferring to a remote location, providing a safety net for web development projects.
#!/bin/bash
# --- Configuration Variables ---
WEBSITE_ROOT="/var/www/html" # Path to your website's root directory
BACKUP_DIR="/opt/backups/website" # Directory to store backups locally
DATE=$(date +%Y%m%d%H%M%S)
BACKUP_FILENAME="website_backup_${DATE}.tar.gz"
# Remote transfer optional (uncomment and configure if needed)
# REMOTE_USER="backupuser"
# REMOTE_HOST="your_backup_server_ip"
# REMOTE_PATH="/mnt/remote_backups/"
# --- Create Backup Directory ---
mkdir -p "$BACKUP_DIR"
# --- Create Compressed Archive of Website Files ---
echo "Starting backup of $WEBSITE_ROOT..."
cd "$WEBSITE_ROOT" || { echo "Error: Website root directory not found."; exit 1; }
sudo tar -czf "${BACKUP_DIR}/${BACKUP_FILENAME}" . || { echo "Error: Failed to create tar archive."; exit 1; }
echo "Backup created: ${BACKUP_DIR}/${BACKUP_FILENAME}"
# --- Transfer Backup to Remote Server (Optional) ---
# if [ -n "$REMOTE_HOST" ] && [ -n "$REMOTE_USER" ] && [ -n "$REMOTE_PATH" ]; then
# echo "Transferring backup to remote server: ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PATH}"
# scp "${BACKUP_DIR}/${BACKUP_FILENAME}" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PATH}"
# if [ $? -eq 0 ]; then
# echo "Remote transfer successful."
# else
# echo "Error: Remote transfer failed." >&2
# fi
# fi
# --- Clean Up Old Backups (Optional) ---
# Keep last 7 days of backups
echo "Cleaning up old backups (keeping last 7 days)..."
find "$BACKUP_DIR" -type f -name "*.tar.gz" -mtime +7 -delete
echo "Website backup process completed."
How it works: This script performs a simple backup of a website's files. It navigates to the specified website root directory, then creates a compressed tar archive of all its contents. The archive is stored in a designated local backup directory. Optionally, the script can be extended to transfer the backup to a remote server using `scp` for off-site storage. A cleanup step is included to remove old backups, managing disk space efficiently. This is crucial for disaster recovery and maintaining data integrity.