BASH
Sync Local Changes to Remote Server with rsync
Perform incremental file synchronization from a local development environment to a remote server using rsync for efficient and fast deployments.
#!/bin/bash
# Configuration
LOCAL_PATH="./dist/" # Path to your local build or project directory
REMOTE_USER="your_username" # SSH username on the remote server
REMOTE_HOST="your_remote_server.com" # IP address or hostname of the remote server
REMOTE_PATH="/var/www/html/" # Destination path on the remote server
# Optional: Create an .rsyncignore file in your local project root
# Example .rsyncignore content:
# .git
# node_modules/
# .env
# *.log
# temp/
EXCLUDE_FILE=".rsyncignore"
# Check if rsync is installed
if ! command -v rsync &> /dev/null
then
echo "rsync could not be found. Please install it (e.g., sudo apt install rsync)."
exit 1
fi
echo "Synchronizing files from $LOCAL_PATH to $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"
# Construct rsync command
RSYNC_CMD="rsync -avz --delete --checksum"
if [ -f "$EXCLUDE_FILE" ]; then
RSYNC_CMD="$RSYNC_CMD --exclude-from='$EXCLUDE_FILE'"
echo "Using exclude file: $EXCLUDE_FILE"
fi
RSYNC_CMD="$RSYNC_CMD $LOCAL_PATH $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"
# Execute rsync
eval $RSYNC_CMD
if [ $? -eq 0 ]; then
echo "File synchronization completed successfully."
else
echo "File synchronization failed. Check for errors above."
fi
How it works: This script automates the process of synchronizing local project files to a remote server using `rsync`. The `-avz` flags enable archive mode (preserving permissions, timestamps, etc.), verbose output, and compression. `--delete` removes extraneous files from the destination, and `--checksum` ensures files are truly identical. It optionally uses an `.rsyncignore` file to exclude unnecessary development files (like `.git` or `node_modules`), making deployments faster and more efficient by only transferring changed data.