BASH

Sync Local Directory to Remote Server with rsync

Automate efficient and incremental file synchronization from your local machine to a remote web server using rsync over SSH, perfect for deployments.

#!/bin/bash

LOCAL_DIR="/path/to/local/project"
REMOTE_USER="your_user"
REMOTE_HOST="your_server_ip"
REMOTE_DIR="/var/www/html/your_website"

# --archive: recursive, preserves permissions, ownership, timestamps, etc.
# --compress: compresses file data during transfer
# --delete: deletes extraneous files from destination dir (not in source)
# --progress: show progress during transfer
# --exclude: exclude specific files/directories (e.g., node_modules, .git)
rsync -avz --delete --exclude 'node_modules/' --exclude '.git/' --exclude 'vendor/' "$LOCAL_DIR/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/"

if [ $? -eq 0 ]; then
    echo "Deployment successful to $REMOTE_HOST:$REMOTE_DIR"
else
    echo "Deployment failed."
fi
How it works: This script uses `rsync` to efficiently synchronize a local project directory to a remote web server via SSH. It's configured for typical web deployments, excluding common development-related directories (like `node_modules`, `.git`, `vendor`) and ensuring only changed files are transferred. The `--delete` flag removes files from the destination that no longer exist in the source, keeping the remote clean. Error handling is included to confirm the deployment's success or failure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs