Website Vidya
Linux & ServersStep-by-Step Guide

How to Transfer Files with Rsync over SSH: Sync, Mirror, and Resume

Learn rsync over ssh with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
How to Transfer Files with Rsync over SSH: Sync, Mirror, and Resume
AI Executive SummaryWebsiteVidya AI

10 min read

Learn rsync over ssh with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What rsync Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Interactive Builder for this Guide

Build your custom rsync syntax (How to Transfer Files with Rsync over SSH: Sync, Mirror, and Resume)

Generated POSIX Command
rsync -azv --progress -h --dry-run -e ssh --exclude=.git /var/www/html/ [email protected]:/var/www/html/
Synchronizes /var/www/html/ -> [email protected]:/var/www/html/ (safe dry-run preview).
Flag-by-Flag Breakdown
-aArchive mode: recursive + preserve symlinks, permissions, timestamps, owner
-zCompress payload data during transfer
-vVerbose file-by-file progress
--progress -hShow per-file transfer speed in human-readable units
--dry-runSimulate changes without writing or deleting any files
-e sshTransport transfer securely over SSH (port 22)
--exclude=.gitSkip matching paths during sync

Mastering rsync over ssh provides system administrators and DevOps engineers with the gold standard solution for remote data synchronization, server migration, and incremental backups. Created by Andrew Tridgell and Paul Mackerras in 1996, rsync revolutionized data movement by implementing a mathematical delta-transfer algorithm that copies only the modified byte blocks of files across network links.

While traditional file copy tools (like scp or cp) transfer entire multi-gigabyte files unconditionally—even if only a single byte changed—rsync calculates block-level checksums, transmitting strictly the difference between source and destination files. When combined with OpenSSH as its transport layer, rsync inherits robust cryptographic encryption, public key authentication, proxy tunneling, and automated key management without requiring an unencrypted standalone rsync daemon.

Whether deploying website updates to production web clusters, synchronizing multi-terabyte database snapshots across availability zones, or maintaining space-efficient rolling daily backups using hardlinks (--link-dest), rsync over SSH delivers unmatched efficiency, reliability, and security.

Advertisement
How to Transfer Files with Rsync over SSH: Sync, Mirror, and Resume — syntax, flags, and practical terminal workflow diagram
How to Transfer Files with Rsync over SSH: Sync, Mirror, and Resume — command syntax, key options, and production workflow reference.

What rsync Does and When to Use It

Under the hood, rsync over SSH operates as a client-server architecture running two cooperating rsync processes. When you run rsync -e ssh, the local rsync client launches a child OpenSSH process that connects to the remote host and spawns a remote rsync server process (e.g., ssh user@host rsync --server). Communication flows over standard input and output pipes encrypted within the SSH session.

The delta-transfer algorithm operates in three distinct phases: the receiver divides an existing target file into non-overlapping blocks of size S (typically 512 to 2048 bytes), computes two checksums for each block—a fast 32-bit rolling checksum (similar to Adler-32) and a strong 128-bit MD4/MD5 hash—and transmits these checksums back to the sender. The sender computes rolling checksums across all overlapping windows of the source file; when a match is found, it confirms with the strong hash and transmits only the unmatched data bytes along with block reconstruction offsets, minimizing WAN bandwidth consumption.

At the operating system level, rsync interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running rsync in cloud instances or Kubernetes worker nodes, combining flags such as -a, -v, -z, -P lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The rsync utility is packaged in rsync across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether rsync is installed and inspect which binary path and version your shell resolves:

type -a rsync
rsync --version 2>/dev/null || man -f rsync

# Illustrative output (reviewed against documentation)
rsync is /usr/bin/rsync
rsync (rsync)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y rsync

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y rsync

# Arch Linux
sudo pacman -S --noconfirm rsync

# Alpine Linux
sudo apk add --no-cache rsync

Command Syntax, Arguments, and Exit Status Codes

rsync [OPTIONS] -e ssh [SRC] [DEST]

The invocation syntax follows: rsync [OPTIONS] -e ssh SOURCE DESTINATION. Paths can be local paths (/path/to/dir) or remote paths (user@host:/path/to/dir). In modern rsync versions, -e ssh is the default remote shell transport, but specifying it explicitly allows custom SSH options (such as -e 'ssh -p 2222 -i /path/to/key').

The trailing slash on source directories is syntactically critical in rsync: specifying a trailing slash on the source (rsync -a /src/ /dst/) copies the contents of /src into /dst. Omitting the trailing slash (rsync -a /src /dst/) creates a new directory named src inside /dst (resulting in /dst/src). Master flags include -a (archive mode), -v (verbose), -z (compression), -P (progress and partial resume), --delete (mirroring), and -n (--dry-run).

  • 0 — Successful execution; all files synchronized cleanly with no transfer errors.
  • 1 — Syntax or usage error; invalid command-line flag or parameter.
  • 2 — Protocol incompatibility or remote rsync binary missing.
  • 10 — Socket I/O error; connection unexpectedly reset or timed out.
  • 11 — File I/O error; disk full, permission denied, or unable to create local/remote file.
  • 23 — Partial transfer; some files or attributes could not be transferred due to permission restrictions.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-a--archiveEnables archive mode; equivalent to -rlptgoD (recursive, symlinks, permissions, times, owner, group, devices).
-v--verboseIncreases verbosity, displaying names of synchronized files and transfer summaries.
-z--compressCompresses file data during transfer to reduce network bandwidth consumption.
-P--partial --progressCombines --progress (displays live transfer progress) and --partial (keeps partial files to resume interrupted transfers).
-e COMMAND--rsh=COMMANDSpecifies the remote shell command to use (e.g., -e 'ssh -p 2222 -i ~/.ssh/key').
--delete--deleteDeletes extraneous files from the destination directory that no longer exist in the source directory (true mirroring).
-n--dry-runPerforms a simulation run that shows what changes would occur without modifying or deleting any files.
--exclude=PATTERN--excludeExcludes files and directories matching PATTERN (e.g., --exclude='*.log' or --exclude='.git/').
-h--human-readableOutputs numbers, transfer rates, and byte sizes in human-readable units (K, M, G).

Archive mode (-a) is the foundation of almost every rsync command. It combines recursion (-r), symbolic link copying (-l), permission preservation (-p), timestamp preservation (-t), owner preservation (-o), group preservation (-g), and device/special file preservation (-D). This ensures mirrored files retain identical metadata on the destination host.

Advertisement

The --delete flag turns rsync into an exact mirror, removing stale files from the target directory. Because an erroneous path or missing trailing slash combined with --delete can wipe out unintended directories, ALWAYS execute a dry run using -n (e.g., rsync -avzn --delete ...) before executing actual deletions.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Synchronize a Local Directory to a Remote Server over SSH

Copy the contents of a local web directory to a remote server with archive mode and compression.

rsync -avz -e ssh /var/www/html/ [email protected]:/var/www/html/

# Illustrative output (reviewed against documentation)
sending incremental file list
./
index.html
about.html
assets/style.css
assets/logo.png

sent 142,510 bytes  received 1,240 bytes  95,833.33 bytes/sec
total size is 452,100  speedup is 3.14

Archive mode (-a) preserves permissions and timestamps, -z compresses in transit, and the trailing slash on /html/ syncs its contents.

2. Synchronize a Remote Directory to a Local Backup Directory

Pull a remote application data directory down to a local backup server over encrypted SSH.

rsync -avz -e ssh [email protected]:/opt/app/data/ /backups/app_data/

# Illustrative output (reviewed against documentation)
receiving incremental file list
./
users.db
cache/metadata.json

sent 2,410 bytes  received 1,842,500 bytes  527,117.14 bytes/sec
total size is 8,420,100  speedup is 4.56

Rsync evaluates existing local files, downloads only new or modified files, and updates the local /backups/app_data/ directory.

3. Transfer Over Custom SSH Port with Specific Identity Key

Connect to an SSH daemon running on port 2222 using an isolated Ed25519 deployment key.

rsync -avzP -e "ssh -p 2222 -i ~/.ssh/backup_key" /srv/storage/ [email protected]:/srv/storage/

# Illustrative output (reviewed against documentation)
sending incremental file list
database_archive.tar.gz
     45.21M 100%   14.82MB/s    0:00:03 (xfr#1, to-chk=0/1)

sent 45,240,110 bytes  received 35 bytes  11,310,036.25 bytes/sec
total size is 45,210,000  speedup is 1.00

The -e option passes custom SSH port and key arguments. The -P flag prints live transfer speed and enables resumption.

4. Simulate a Mirror Synchronization with Dry-Run Mode

Preview exactly which files would be transferred or deleted without making any actual changes on disk.

rsync -avzn --delete -e ssh /var/www/ [email protected]:/var/www/

# Illustrative output (reviewed against documentation)
sending incremental file list
deleting old_banner.jpg
index.html
assets/new_style.css

sent 1,240 bytes  received 120 bytes  906.67 bytes/sec
total size is 120,400  speedup is 88.53 (DRY RUN)

The -n (--dry-run) option simulates the transfer, displaying that old_banner.jpg would be deleted and new_style.css copied.

5. Mirror Directories and Delete Obsolete Files on Destination

Enforce exact directory mirroring by deleting files on the destination that no longer exist on the source.

rsync -avz --delete -e ssh /srv/media/ [email protected]:/srv/media/

# Illustrative output (reviewed against documentation)
sending incremental file list
deleting obsolete_video.mp4
updated_catalog.json

sent 4,120 bytes  received 150 bytes  2,846.67 bytes/sec
total size is 14,210,000  speedup is 3,327.87

The --delete option removes obsolete_video.mp4 from the target server, maintaining perfect synchronization.

6. Exclude Specific Files and Directories Using Patterns

Filter out Git repositories, temporary log files, and cache directories from the synchronization.

rsync -avz --exclude="*.log" --exclude=".git/" --exclude="node_modules/" -e ssh ./app/ [email protected]:/opt/app/

# Illustrative output (reviewed against documentation)
sending incremental file list
./
package.json
src/server.js
src/routes.js

sent 18,420 bytes  received 450 bytes  12,580.00 bytes/sec
total size is 42,100  speedup is 2.23

The --exclude directives prevent large .git histories, logs, and node_modules from being transferred across the network.

Real-World Workflows, Pipelines, and Shell Automation

Automated Zero-Downtime Web Application Deployment Pipeline

Deploy application source code to a remote production cluster using rsync over SSH, excluding local build caches and staging files.

#!/usr/bin/env bash
set -euo pipefail

SOURCE_DIR="./build/"
REMOTE_HOST="web01.example.com"
REMOTE_USER="deploy"
REMOTE_DIR="/var/www/app_release"
SSH_KEY="~/.ssh/deploy_key"

echo "=== 1. Verifying Local Build Output ==="
if [ ! -d "${SOURCE_DIR}" ]; then
  echo "Error: Build directory ${SOURCE_DIR} not found!"
  exit 1
fi

echo "=== 2. Running Dry-Run Synchronization Preview ==="
rsync -avzn --delete \
  -e "ssh -i ${SSH_KEY}" \
  --exclude=".env.local" \
  --exclude="*.map" \
  "${SOURCE_DIR}" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/"

echo "=== 3. Executing Production Synchronization ==="
rsync -avz --delete \
  -e "ssh -i ${SSH_KEY}" \
  --exclude=".env.local" \
  --exclude="*.map" \
  "${SOURCE_DIR}" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/"

echo "=== 4. Reloading Web Server Daemons ==="
ssh -i "${SSH_KEY}" "${REMOTE_USER}@${REMOTE_HOST}" "sudo systemctl reload nginx"
echo "Deployment completed successfully."

# Illustrative output (reviewed against documentation)
=== 1. Verifying Local Build Output ===
=== 2. Running Dry-Run Synchronization Preview ===
sending incremental file list
index.html
assets/app.js (DRY RUN)
=== 3. Executing Production Synchronization ===
sending incremental file list
index.html
assets/app.js
sent 45,210 bytes  received 840 bytes  30,700.00 bytes/sec
=== 4. Reloading Web Server Daemons ===
Deployment completed successfully.

This production deployment script executes a dry-run check, syncs application files with rsync over SSH, and reloads Nginx cleanly.

Space-Efficient Incremental Daily Backup Pipeline Using --link-dest

Maintain daily rolling snapshot backups of a remote server where unchanged files share hardlinks, consuming zero additional disk space for duplicate files.

#!/usr/bin/env bash
set -euo pipefail

REMOTE_SERVER="prod.example.com"
REMOTE_PATH="/var/data/"
BACKUP_ROOT="/backups/daily"
TODAY=$(date +%Y-%m-%d)
YESTERDAY=$(date -d "yesterday" +%Y-%m-%d 2>/dev/null || date -v-1d +%Y-%m-%d)

TARGET_DIR="${BACKUP_ROOT}/${TODAY}"
LATEST_LINK="${BACKUP_ROOT}/${YESTERDAY}"

mkdir -p "${TARGET_DIR}"

LINK_OPT=""
if [ -d "${LATEST_LINK}" ]; then
  echo "Linking unchanged files against yesterday's snapshot: ${LATEST_LINK}"
  LINK_OPT="--link-dest=${LATEST_LINK}"
fi

echo "=== Starting Incremental Snapshot for ${TODAY} ==="
rsync -avz ${LINK_OPT} \
  -e ssh \
  --delete \
  "backup@${REMOTE_SERVER}:${REMOTE_PATH}" "${TARGET_DIR}/"

echo "Snapshot completed at ${TARGET_DIR}."

# Illustrative output (reviewed against documentation)
Linking unchanged files against yesterday's snapshot: /backups/daily/2026-10-21
=== Starting Incremental Snapshot for 2026-10-22 ===
receiving incremental file list
./
users/profile_1842.png
sent 1,240 bytes  received 145,200 bytes  41,840.00 bytes/sec
Snapshot completed at /backups/daily/2026-10-22.

The --link-dest option creates hardlinks to yesterday's files for unchanged assets, creating complete daily recovery snapshots with minimal disk space.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding rsync inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Running rsync over SSH eliminates the need to expose the unencrypted rsync daemon (TCP port 873) to the network. All traffic is secured within the encrypted SSH tunnel, benefiting from key-based authentication and fail2ban brute-force protection.

For automated backup servers, restrict the SSH key using an authorized_keys Forced Command with rrsync (restricted rsync). The rrsync script restricts the incoming SSH key strictly to read-only or write-only rsync operations within a specified directory jail.

GNU/Linux, BSD, and BusyBox Implementation Differences

Rsync is supported across Linux, FreeBSD, OpenBSD, NetBSD, and macOS. However, macOS includes an ancient GPLv2 build of rsync (version 2.6.9 from 2006) that lacks modern options like --info=progress2 and extended attribute flags. macOS users should install modern rsync via Homebrew (brew install rsync).

Crucially, rsync must be installed on BOTH the local client machine and the remote destination host. If the remote host lacks the rsync binary, rsync over SSH will fail with 'bash: rsync: command not found'.

Troubleshooting Common Errors and Diagnostics

bash: rsync: command not found (remote host error)

Root Cause: The rsync binary is not installed on the remote destination server.

Resolution: Install rsync on the remote host via apt-get install rsync or dnf install rsync.

ssh user@remote-host "sudo apt-get update && sudo apt-get install -y rsync"

Unexpected directory nesting (destination has /dst/src/ instead of /dst/)

Root Cause: The source directory argument omitted the trailing slash (e.g., rsync -a /src /dst instead of rsync -a /src/ /dst).

Resolution: Add a trailing slash to the source path to copy the directory's contents rather than the directory itself.

rsync -avz /local/dir/ user@remote-host:/remote/dir/

rsync error: some files/attrs were not transferred (code 23)

Root Cause: The remote user lacks permission to write to certain files or set owner/group attributes.

Resolution: Transfer with sudo privileges using --rsync-path='sudo rsync' or pass --no-owner --no-group.

rsync -avz --no-owner --no-group /local/dir/ user@remote-host:/remote/dir/

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
A trailing slash on the source directory copies the contents of the folder into the destination: rsync -a /src/ /dst/ creates /dst/file.txt. Omitting the trailing slash copies the directory itself: rsync -a /src /dst/ creates /dst/src/file.txt.
Rsync automatically resumes file transfers if you use the -P (or --partial --progress) option. It keeps partially transferred files on disk and resumes from the exact byte offset where the connection was severed.
Pass the port inside the -e option: rsync -avz -e 'ssh -p 2222' /local/dir/ user@host:/remote/dir/.
When rsync finds that a source file matches an existing file in the --link-dest directory (identical size and timestamp), it creates a filesystem hardlink instead of copying the file. Hardlinks point to the same physical disk inode, taking up zero extra storage.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout