BASH
Deploy Website Files with Rsync
Efficiently deploy your website's updated files to a remote server using rsync over SSH, ensuring only changed files are transferred for faster deployments.
#!/bin/bash
# Configuration Variables
LOCAL_PATH="/path/to/your/local/website"
REMOTE_USER="your_ssh_user"
REMOTE_HOST="your_server_ip_or_domain"
REMOTE_PATH="/var/www/your_website"
# Optional: Exclude files/directories (e.g., node_modules, .git, local config files)
# Create an 'exclude-list.txt' in your LOCAL_PATH with one pattern per line:
# node_modules/
# .git/
# .env.local
EXCLUDE_FILE="$LOCAL_PATH/exclude-list.txt"
echo "Starting deployment to $REMOTE_HOST:$REMOTE_PATH..."
# Check if exclude file exists
EXCLUDE_OPTION=""
if [ -f "$EXCLUDE_FILE" ]; then
EXCLUDE_OPTION="--exclude-from=$EXCLUDE_FILE"
echo "Using exclude file: $EXCLUDE_FILE"
fi
# Rsync command
# -a: archive mode (preserves permissions, ownership, timestamps, etc.)
# -v: verbose output
# -z: compress file data during transfer
# --delete: delete extraneous files from destination dirs (i.e., files that don't exist in source)
# -e ssh: use SSH as the remote shell
rsync -avz --delete $EXCLUDE_OPTION \
"$LOCAL_PATH/" \
"$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/"
if [ $? -eq 0 ]; then
echo "Deployment successful!"
else
echo "ERROR: Deployment failed!"
echo "Please check your rsync configuration, SSH connection, and paths."
fi
echo "Deployment process finished."
How it works: This script automates the deployment of website files to a remote server using `rsync` over SSH. `rsync` is highly efficient as it only transfers files that have changed, making deployments faster than full transfers. The script uses the `-avz` flags for archive mode (preserving file attributes), verbose output, and compression. The `--delete` flag ensures that files removed locally are also removed from the remote server, keeping the destination in sync. It also supports an optional `exclude-list.txt` to prevent specific files or directories (like `.git` or `node_modules`) from being deployed. Using SSH keys for authentication is recommended for seamless, passwordless execution.