BASH

Deploy Static Files with Rsync over SSH

Automate static website deployments with this bash script using `rsync` over SSH. It efficiently transfers and synchronizes files to a remote server.

#!/bin/bash

# --- Configuration ---
LOCAL_DIR="./dist/"                  # Local directory to sync (e.g., your build output)
REMOTE_USER="your_ssh_user"          # SSH username for the remote server
REMOTE_HOST="your_remote_server_ip_or_domain" # Remote server IP or domain
REMOTE_PATH="/var/www/html/mysite/"  # Remote directory where files will be deployed
SSH_KEY_PATH="~/.ssh/id_rsa"         # Path to your private SSH key (optional)

# --- Script Logic ---
echo "Starting deployment to ${REMOTE_HOST}:${REMOTE_PATH}"

# Check if local directory exists
if [ ! -d "${LOCAL_DIR}" ]; then
    echo "Error: Local directory '${LOCAL_DIR}' not found. Please build your project first."
    exit 1
fi

# Use rsync to synchronize files
# -a: archive mode (preserves permissions, timestamps, etc.)
# -v: verbose output
# -z: compress file data during transfer
# --delete: delete extraneous files from destination dirs (optional, use with caution)
# -e "ssh -i ${SSH_KEY_PATH}": specify SSH command with identity file (if not using default)

RSYNC_CMD="rsync -avz --delete"

if [ -f "${SSH_KEY_PATH}" ]; then
    RSYNC_CMD+=" -e \"ssh -i ${SSH_KEY_PATH}\""
else
    RSYNC_CMD+=" -e ssh"
fi

eval "${RSYNC_CMD} ${LOCAL_DIR} ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PATH}"

if [ $? -eq 0 ]; then
    echo "Deployment successful!"
else
    echo "Deployment failed. Please check rsync output and configurations."
    exit 1
fi

echo "Deployment script finished."
How it works: This script uses `rsync` to efficiently deploy static website files from a local build directory to a remote server over SSH. It synchronizes files, transferring only changes and optionally deleting extraneous files on the destination. It supports specifying an SSH key for authentication and provides verbose output.

Need help integrating this into your project?

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

Hire DigitalCodeLabs