BASH
Deploy Static Web Content with Rsync
Efficiently deploy static website files from a local directory to a remote server using rsync, ensuring only changed files are transferred for faster updates.
#!/bin/bash
deploy_static_content() {
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ]; then
echo "Usage: deploy_static_content <local_path> <remote_user> <remote_host> <remote_path>"
return 1
fi
LOCAL_PATH="$1"
REMOTE_USER="$2"
REMOTE_HOST="$3"
REMOTE_PATH="$4"
if [ ! -d "$LOCAL_PATH" ]; then
echo "Error: Local path '$LOCAL_PATH' not found."
return 1
fi
echo "Deploying '$LOCAL_PATH' to '$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH'..."
# -a: archive mode (preserves permissions, ownership, timestamps, etc.)
# -v: verbose
# -z: compress file data during transfer
# --delete: delete extraneous files from dest dir (not in src)
rsync -avz --delete "$LOCAL_PATH/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/"
if [ $? -eq 0 ]; then
echo "Deployment successful."
else
echo "Deployment failed!"
fi
}
# To use:
# deploy_static_content ./build myuser mydomain.com /var/www/html/mysite
How it works: This script automates the deployment of static web content to a remote server using `rsync`. It takes the local source path, remote user, remote host, and remote destination path as arguments. The `rsync` command, with options like `-avz --delete`, efficiently synchronizes files by transferring only the differences, compressing data during transfer, and ensuring the remote directory mirrors the local one by deleting extraneous files. This is ideal for fast and reliable static site deployments.