BASH

Securely Sync Files to a Remote Server with rsync

Learn to use `rsync` in a Bash script for efficient, secure, and incremental file synchronization to a remote server, perfect for website deployments.

#!/bin/bash
LOCAL_PATH="/path/to/your/local/app"
REMOTE_USER="webuser"
REMOTE_HOST="your-web-server.com"
REMOTE_PATH="/var/www/html/your-app"
EXCLUDE_FILE="/path/to/your/local/app/.rsyncignore" # Optional: specify files/dirs to exclude

# Check if exclude file exists
if [ -f "$EXCLUDE_FILE" ]; then
    EXCLUDE_OPT="--exclude-from=$EXCLUDE_FILE"
else
    EXCLUDE_OPT=""
fi

echo "Starting rsync deployment to $REMOTE_HOST..."

# The -avz options mean:
# -a: archive mode (recursively, preserve permissions, ownership, etc.)
# -v: verbose output
# -z: compress file data during the transfer
# --delete: delete extra files from destination (files that don't exist in source)
# --progress: show progress during transfer
# --partial: keep partially transferred files (allows resuming)
# --stats: give a summary of the transfer
rsync -avz --delete --progress --partial --stats $EXCLUDE_OPT "$LOCAL_PATH/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

if [ $? -eq 0 ]; then
    echo "Rsync deployment completed successfully to $REMOTE_HOST."
else
    echo "Rsync deployment failed!" >&2
    exit 1
fi
How it works: This script uses `rsync` to synchronize local application files to a remote web server. It defines local and remote paths, user, and host. It includes an optional mechanism to use an .rsyncignore file for excluding specific files or directories from the transfer. The `rsync` command uses archive mode (-a), verbosity (-v), compression (-z), and delete to ensure the remote directory mirrors the local one, providing an efficient way to deploy or back up web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs