rsync
is a sysadmin's best friend. It's a powerful and versatile tool for copying and synchronizing files and directories, whether locally or remotely. The real magic of rsync
is its ability to transfer only the parts of a file that have changed, making it incredibly efficient. Here are the most common rsync
commands you'll need, broken down for quick reference.
1. Copy a Single File
This is a simple copy operation. We'll use the -avP
flags, which are a great habit to get into.
-a
(archive): Preserves permissions, ownership, and timestamps.-v
(verbose): Shows what’s happening in real time.-P
(progress & partial): Displays a progress bar and allows you to resume an interrupted transfer.
rsync -avP /path/to/local/file.zip user@remote_server:/path/to/remote/directory/
2. Copy a Directory
When copying a directory, the placement of the trailing slash is critical.
- To copy the contents of a directory: Use a trailing slash (
/
). This puts all the files and subdirectories directly into the destination.
rsync -avP /path/to/local/directory/ user@remote_server:/path/to/remote/directory/
- To copy the directory itself: Omit the trailing slash. This will create the local directory and its contents inside the remote directory.
rsync -avP /path/to/local/directory user@remote_server:/path/to/remote/directory/
3. Synchronize a Directory
This command is the gold standard for backups. It makes the destination directory an exact replica of the source by deleting files on the destination that no longer exist on the source.
--delete
: Deletes extraneous files from the destination. Use this with caution!
rsync -avP --delete /path/to/local/directory/ user@remote_server:/path/to/remote/directory/
4. Copy While Excluding Files or Directories
Sometimes you don't need to copy everything. The --exclude
flag lets you skip files or directories that you don't want to transfer.
--exclude
: Excludes files or directories that match the specified pattern. You can use this flag multiple times.
rsync -avP --exclude 'logs/*' --exclude 'cache/' /path/to/local/directory/ user@remote_server:/path/to/remote/directory/
5. Do a "Dry Run"
Before you run a complex rsync
command, especially one with the --delete
flag, do a dry run. It simulates the transfer and shows you exactly what would happen without making any changes.
--dry-run
: Simulates the transfer. You can also use the shorthand-n
.
rsync -avP --dry-run /path/to/local/directory/ user@remote_server:/path/to/remote/directory/
6. Copy Files from a Remote Server (Pull)
rsync
works in both directions. You can "pull" files from a remote server to your local system by simply reversing the source and destination paths.
rsync -avP user@remote_server:/path/to/remote/directory/ /path/to/local/directory/