BASH

Efficiently Syncing Local Files to a Remote Server with Rsync

Leverage rsync for fast, incremental file synchronization to deploy web application updates or backups to a remote server, saving bandwidth and time.

#!/bin/bash

# Configuration
LOCAL_PATH="/path/to/your/local/webapp"
REMOTE_USER="your_ssh_user"
REMOTE_HOST="your_remote_server_ip_or_domain"
REMOTE_PATH="/var/www/your_webapp_root"

# Exclude files/directories (e.g., node_modules, .git, .env, storage/logs)
# Add more as needed, relative to LOCAL_PATH
EXCLUDE_LIST=(
  "node_modules/"
  ".git/"
  ".env"
  "storage/logs/"
  "vendor/"
)

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

# Rsync command
# -a: archive mode (preserves permissions, timestamps, etc.)
# -v: verbose output
# -z: compress file data during the transfer
# -r: recurse into directories (part of -a, but explicit doesn't hurt)
# --delete: delete extraneous files from dest dirs (careful with this!)
# --progress: show progress during transfer
# -h: human-readable numbers

echo "Starting rsync from $LOCAL_PATH to $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

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

if [ $? -eq 0 ]; then
  echo "Rsync completed successfully."
else
  echo "Rsync encountered errors."
fi
How it works: This script uses `rsync` to efficiently synchronize a local web application directory with a remote server. `rsync` is ideal for deployments because it only transfers changed files or parts of files, making it much faster than copying everything. The script includes an `EXCLUDE_LIST` to prevent transferring unnecessary files like `node_modules` or `.git` directories. The `-avzh --delete --progress` options ensure an archive transfer, verbose output, compression, human-readable sizes, deletion of remote files not present locally, and progress display. Adjust local/remote paths and the exclude list as necessary.

Need help integrating this into your project?

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

Hire DigitalCodeLabs