BASH

Synchronize Local Files to Remote Server with rsync

Efficiently deploy and synchronize local website files to a remote server using rsync, transferring only changed files and excluding specific patterns for faster updates.

#!/bin/bash

LOCAL_PATH="./public/"
REMOTE_USER="your_user"
REMOTE_HOST="your_server.com"
REMOTE_PATH="/var/www/html/"

# Optional: Add paths to exclude from synchronization
# For example, local development files, Git files, etc.
EXCLUDE_LIST=(
  "node_modules/"
  ".git/"
  ".env"
  "*.bak"
)

# Build the exclude options for rsync
RSYNC_EXCLUDES=""
for item in "${EXCLUDE_LIST[@]}"; do
  RSYNC_EXCLUDES+="--exclude=$item "
done

# Check if local path exists
if [ ! -d "$LOCAL_PATH" ]; then
  echo "Error: Local path $LOCAL_PATH not found."
  exit 1
fi

echo "Synchronizing files from $LOCAL_PATH to $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

# -avz: Archive mode, verbose, compress
# --delete: Delete files on the remote side that don't exist on the local side (USE WITH CAUTION!)
# --progress: Show progress during transfer
# $RSYNC_EXCLUDES: Apply exclusion rules

rsync -avz --progress --delete $RSYNC_EXCLUDES "$LOCAL_PATH" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

if [ $? -eq 0 ]; then
  echo "Synchronization complete."
else
  echo "Synchronization failed."
  exit 1
fi
How it works: This script leverages `rsync` to efficiently synchronize a local directory to a remote server. It uses archive mode for preserving permissions and timestamps, compresses data during transfer, and supports excluding specific files or directories (like `node_modules` or `.git`) to prevent unwanted files from being deployed. The `--delete` flag (use with caution) ensures the remote matches the local directory, removing files no longer present locally, making it ideal for deployments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs