BASH

Deploying Static Website via rsync with Exclusions and Dry Run

Automate static website deployments with 'rsync', using powerful features like file exclusions, deletion of old files, and a 'dry run' mode for safe synchronization.

#!/bin/bash

# Configuration
LOCAL_BUILD_DIR="./public"
REMOTE_USER="webmaster"
REMOTE_HOST="your_server_ip_or_domain"
REMOTE_DEST_DIR="/var/www/html/your_site"

# Exclude list for rsync (relative to LOCAL_BUILD_DIR)
EXCLUDE_FILE="rsync-exclude.txt"

# Create a dummy exclude file for demonstration if it doesn't exist
if [ ! -f "$EXCLUDE_FILE" ]; then
  echo "temp_file.txt" > "$EXCLUDE_FILE"
  echo ".DS_Store" >> "$EXCLUDE_FILE"
  echo "node_modules/" >> "$EXCLUDE_FILE"
  echo "Created a sample $EXCLUDE_FILE."
fi

# Check if the local build directory exists
if [ ! -d "$LOCAL_BUILD_DIR" ]; then
  echo "Error: Local build directory '$LOCAL_BUILD_DIR' not found." >&2
  echo "Please run your build command first (e.g., 'npm run build')." >&2
  exit 1
fi

# Dry run for verification
echo "--- Performing Dry Run (no changes will be made) ---"
rsync -avz --dry-run --delete --exclude-from="$EXCLUDE_FILE" \
      "$LOCAL_BUILD_DIR/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DEST_DIR/"

if [ $? -eq 0 ]; then
  echo "
Dry run completed successfully. Review the changes above."
  read -p "Proceed with actual deployment? (y/N) " CONFIRM
  if [[ "$CONFIRM" =~ ^[yY]$ ]]; then
    echo "--- Starting Actual Deployment ---"
    rsync -avz --delete --exclude-from="$EXCLUDE_FILE" \
          "$LOCAL_BUILD_DIR/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DEST_DIR/"
    if [ $? -eq 0 ]; then
      echo "Deployment successful!"
    else
      echo "Error: Deployment failed." >&2
      exit 1
    fi
  else
    echo "Deployment cancelled."
    exit 0
  fi
else
  echo "Error during dry run. Aborting deployment." >&2
  exit 1
fi

echo "Script finished."
How it works: This script automates the deployment of a static website using `rsync` over SSH. It synchronizes files from a local build directory to a remote server, ensuring that only necessary files are transferred and that old files on the server are removed. Key features include a `--exclude-from` option to ignore specific files or directories (like temporary files or `node_modules`), the `--delete` flag to remove files on the destination that no longer exist locally, and a crucial `--dry-run` step to preview changes before actual deployment, prompting for user confirmation for safety.

Need help integrating this into your project?

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

Hire DigitalCodeLabs