This script creates an efficient, encrypted off-site copy of a local directory on a remote server. It combines rsync for delta transfers (only changed blocks travel the network) with ssh as the secure transport. After set -euo pipefail and argument validation, it accepts the local path, an user@host target, the remote destination, and an optional SSH port. The rsync flags do the heavy lifting: -a preserves attributes, -z compresses data in transit, -h prints human-readable sizes, --partial lets interrupted transfers resume instead of restarting, --progress shows live status, and --delete keeps the remote an exact mirror. The custom -e ssh string sets the port and uses accept-new to trust unknown hosts on first contact only. Run it as ./remote_sync.sh /data [email protected] /vol/data 2222. Best paired with SSH key authentication so it can run unattended from cron.
Sync a Directory to a Remote Host via rsync over SSH
Mirrors a local directory to a remote server securely over SSH.
1 views
Share
Script
Download .shbash
#!/usr/bin/env bash
#
# remote_sync.sh - Mirror a local directory to a remote host over SSH.
#
# Uses rsync over SSH for efficient, resumable, encrypted off-site backups.
#
# Usage: ./remote_sync.sh <local_dir> <user@host> <remote_dir> [ssh_port]
#
set -euo pipefail
# --- Argument handling --------------------------------------------------------
if [[ $# -lt 3 || $# -gt 4 ]]; then
echo "Usage: $0 <local_dir> <user@host> <remote_dir> [ssh_port]" >&2
exit 1
fi
LOCAL_DIR="$1"
REMOTE="$2"
REMOTE_DIR="$3"
SSH_PORT="${4:-22}"
[[ -d "$LOCAL_DIR" ]] || { echo "Error: local dir '$LOCAL_DIR' not found." >&2; exit 1; }
# --- Run the sync -------------------------------------------------------------
# -a archive, -z compress in transit, -h human-readable, --partial resumes
# interrupted transfers, --delete keeps the remote mirrored to the source.
echo "Syncing '$LOCAL_DIR' -> ${REMOTE}:${REMOTE_DIR} (port $SSH_PORT)"
rsync -azh --partial --progress --delete \
-e "ssh -p ${SSH_PORT} -o StrictHostKeyChecking=accept-new" \
"${LOCAL_DIR%/}/" "${REMOTE}:${REMOTE_DIR%/}/"
echo "Remote sync complete."How to run
Review the script first, then download or copy it and run it in your environment.
You might also like
bashlinuxIntermediate
Backup All MySQL Databases with mysqldump
Dumps each MySQL database to its own compressed SQL file.
bashlinuxIntermediate
Bulk Rename Files by Pattern
Renames many files at once using a sed substitution, with dry-run preview.
bashlinuxIntermediate
Backup All PostgreSQL Databases with pg_dumpall
Dumps the entire PostgreSQL cluster, including roles, to one compressed file.