Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Using rsync - Comprehensive Tutorial

Introduction

rsync is a powerful command-line tool used for synchronizing files and directories between two locations over a network or locally. It is widely used for backups, mirroring, and data transfers due to its efficiency and flexibility.

Installation

Before you can use rsync, you need to ensure it is installed on your system. Here are the installation commands for different operating systems:

On Debian/Ubuntu:

sudo apt-get install rsync

On CentOS/RHEL:

sudo yum install rsync

On macOS:

brew install rsync

Basic Usage

The basic syntax of the rsync command is:

rsync [options] source destination

Here, source is the file or directory you want to copy, and destination is where you want to copy it to.

Example:

Copying a file from one directory to another:

rsync -av /path/to/source/file.txt /path/to/destination/

Common Options

Here are some commonly used options with rsync:

  • -a: Archive mode (preserves permissions, times, symbolic links, etc.)
  • -v: Verbose mode (shows detailed information about the transfer)
  • --delete: Deletes files in the destination that are not in the source
  • --progress: Shows progress during transfer
  • -z: Compresses file data during transfer

Synchronizing Directories

You can synchronize directories using rsync. This is useful for backups and mirroring directories between systems.

Example:

Synchronizing a directory with another:

rsync -av --delete /path/to/source/directory/ /path/to/destination/directory/

Remote Synchronization

rsync can be used to synchronize files between local and remote systems using SSH for secure data transfer.

Example:

Synchronizing a local directory with a remote directory:

rsync -avz -e ssh /path/to/local/directory/ user@remote_host:/path/to/remote/directory/

Synchronizing a remote directory with a local directory:

rsync -avz -e ssh user@remote_host:/path/to/remote/directory/ /path/to/local/directory/

Excluding Files

You can exclude files or directories from being synchronized using the --exclude option.

Example:

Excluding a specific file:

rsync -av --exclude 'file.txt' /path/to/source/ /path/to/destination/

Excluding multiple files or directories using a pattern:

rsync -av --exclude '*.tmp' /path/to/source/ /path/to/destination/

Dry Run

The --dry-run option allows you to simulate the synchronization process without making any changes. This is useful for testing your rsync commands.

Example:

Performing a dry run:

rsync -av --dry-run /path/to/source/ /path/to/destination/

Conclusion

rsync is a versatile tool for file synchronization and backup. By understanding its basic usage and options, you can efficiently manage data transfers and backups both locally and remotely. Experiment with the examples provided and explore additional options to tailor rsync to your specific needs.