How to copy files between Linux servers using rsync
rsync is a file synchronization utility that helps you copy or transfer files locally or to a remote server. It transfers only the differences between source and destination, making repeated syncs fast and bandwidth-efficient.
Installation
rsync is pre-installed on most Linux distributions. If not:
# Debian/Ubuntu
sudo apt-get install rsync
# CentOS/RHEL
sudo yum install rsyncBasic syntax
rsync [options] source destinationLocal copy
rsync -av /source/directory/ /destination/directory/The trailing slash on the source means "copy the contents of this directory". Without it, the directory itself is copied.
Copy to a remote server
rsync -av /local/path/ username@remote-server:/remote/path/Copy from a remote server
rsync -av username@remote-server:/remote/path/ /local/path/Commonly used options
| Option | Description |
|---|---|
-a | Archive mode: preserves permissions, timestamps, symlinks, etc. |
-v | Verbose output |
-z | Compress data during transfer |
-P | Show progress and keep partial files |
--delete | Delete files at the destination that no longer exist at the source |
-n or --dry-run | Simulate the transfer without making changes |
-e ssh | Use SSH as the transport (default for remote transfers) |
Sync with delete (mirror)
To make the destination an exact mirror of the source (removing files deleted from source):
rsync -av --delete /source/ username@remote-server:/destination/Using a specific SSH key
rsync -av -e "ssh -i ~/.ssh/id_ed25519" /local/path/ username@remote-server:/remote/path/Using a non-default SSH port
rsync -av -e "ssh -p 2222" /local/path/ username@remote-server:/remote/path/Dry run first
Always test with --dry-run before a destructive sync:
rsync -av --delete --dry-run /source/ username@remote-server:/destination/Scheduling with cron
To run a nightly backup at 2:00 AM:
0 2 * * * rsync -az --delete /var/www/ backup-server:/backups/www/