BASH

Securely Sync Local Files to Remote Server with Rsync

Automate secure file deployments from your local machine to a remote web server using rsync, ensuring only changed files are transferred efficiently.

#!/bin/bash
SOURCE_DIR="./build/"
REMOTE_USER="your_user"
REMOTE_HOST="your_server.com"
REMOTE_PATH="/var/www/html/"

# Ensure the source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
    echo "Error: Source directory $SOURCE_DIR does not exist."
    exit 1
fi

# Perform rsync operation with common options
# -a: archive mode (preserves permissions, times, etc.)
# -v: verbose
# -z: compress file data during the transfer
# -h: human-readable output
# --delete: delete extraneous files from dest (if you want exact mirror)
# --exclude: exclude specific files/directories
rsync -avzh --delete --exclude 'node_modules/' --exclude '.git/' "$SOURCE_DIR" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

if [ $? -eq 0 ]; then
    echo "Deployment successful to $REMOTE_HOST:$REMOTE_PATH"
else
    echo "Deployment failed."
    exit 1
fi
How it works: This script automates syncing a local directory (e.g., a build output) to a remote web server using `rsync`. It uses archive mode (`-a`) for comprehensive syncing, compresses data (`-z`), and provides verbose output (`-v`). The `--delete` option ensures the remote directory mirrors the local one by removing extra files. It also includes error handling and exclusions for common development files, making it a robust deployment tool.

Need help integrating this into your project?

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

Hire DigitalCodeLabs