BASH

Synchronize Local Directory to Remote Server

A bash script utilizing rsync to efficiently synchronize local web project files with a remote server, ideal for static site deployments or asset updates.

#!/bin/bash

# Usage: ./deploy_sync.sh <local_path> <remote_user@remote_host> <remote_path>

LOCAL_PATH=$1
REMOTE_TARGET=$2 # e.g., [email protected]
REMOTE_PATH=$3   # e.g., /var/www/html/mysite

if [ -z "$LOCAL_PATH" ] || [ -z "$REMOTE_TARGET" ] || [ -z "$REMOTE_PATH" ]; then
  echo "Usage: $0 <local_path> <remote_user@remote_host> <remote_path>"
  echo "Example: $0 ./build [email protected] /var/www/html/mywebapp"
  exit 1
}

# Ensure local path exists
if [ ! -d "$LOCAL_PATH" ]; then
  echo "Error: Local path '$LOCAL_PATH' does not exist or is not a directory."
  exit 1
}

echo "Synchronizing local directory '$LOCAL_PATH' to remote '$REMOTE_TARGET:$REMOTE_PATH'...
"
# rsync options:
# -a: archive mode (recursive, preserves symlinks, permissions, times, group, owner)
# -v: verbose
# -z: compress file data during the transfer
# --delete: delete extraneous files from destination (remote) dir
# --exclude: exclude specific files/directories (e.g., node_modules, .git, .env)
# --progress: show progress during transfer

# IMPORTANT: Make sure the local path ends with a / to sync its *contents*,
#            not the directory itself into a subdirectory on remote.
#            e.g., 'local_dir/' syncs contents, 'local_dir' syncs local_dir into remote.

read -p "Proceed with rsync? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
  rsync -avz --delete --exclude='.git' --exclude='node_modules' --exclude='.env' --progress "$LOCAL_PATH"/ "$REMOTE_TARGET":"$REMOTE_PATH"
  if [ $? -eq 0 ]; then
    echo "Synchronization successful!"
  else
    echo "Synchronization FAILED with exit code $?."
  fi
else
  echo "Rsync aborted."
  exit 0
fi
How it works: This script uses `rsync` to efficiently synchronize a local directory (e.g., a compiled web project build) to a remote server. `rsync` is highly optimized for transferring only changed files, making deployments fast. Key options include `-a` for archive mode (preserving file attributes), `-z` for compression, and `--delete` to remove files on the remote that no longer exist locally, ensuring the remote mirrors the local source. Exclusions (`--exclude`) prevent sensitive or unnecessary files from being transferred. A confirmation prompt is included 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