BASH

Securely Sync Files with rsync over SSH

Master efficient and secure file synchronization between local and remote servers using rsync over SSH. Ideal for deployments or backup mirroring.

#!/bin/bash

# Configuration
LOCAL_PATH="/var/www/mywebsite/public"
REMOTE_USER="remoteuser"
REMOTE_HOST="your_remote_server.com"
REMOTE_PATH="/var/www/mywebsite_staging/public"
SSH_KEY="~/.ssh/id_rsa"

# Example 1: Sync local directory to remote (push)
# rsync -avz --delete -e "ssh -i $SSH_KEY" "$LOCAL_PATH/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

# Example 2: Sync remote directory to local (pull) - useful for backups
rsync -avz -e "ssh -i $SSH_KEY" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/" "$LOCAL_PATH"

if [ $? -eq 0 ]; then
    echo "rsync synchronization completed successfully."
else
    echo "rsync synchronization failed."
fi
How it works: This script demonstrates how to use `rsync` for efficient and secure file synchronization between a local machine and a remote server over SSH. It uses the `-a` (archive mode), `-v` (verbose), `-z` (compress) flags and specifies a private SSH key for authentication. It shows both pushing local changes to a remote server (commented out) and pulling remote changes to a local directory, making it versatile for deployments or backups.

Need help integrating this into your project?

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

Hire DigitalCodeLabs