rsync is a powerful file synchronization and transfer tool used in Linux systems. It allows copying and synchronizing files and directories between different locations, either locally or between remote systems. Below is a step-by-step guide on how to use rsync with practical examples.

1. Installing rsync

In most Linux distributions, rsync comes pre-installed. However, if you need to install it, you can do so with the following command:

For Debian/Ubuntu-based systems:

sudo apt-get update
sudo apt-get install rsync

For Red Hat/CentOS-based systems:

sudo yum install rsync

2. Basic Syntax of rsync

The basic syntax of rsync is as follows:

rsync [options] source destination
  • source: The location of the file or directory you want to copy or synchronize.
  • destination: The location where you want to copy or synchronize the files or directories.

3. Usage Examples

  • Copy a file locally:
    rsync -avh /path/to/file.txt /path/to/destination/
    • -a: Archive mode; preserves permissions, modification times, and links.
    • -v: Verbose mode; shows the progress of the transfer.
    • -h: Human-readable; displays sizes in a readable format.
  • Synchronize a directory locally:
    rsync -avh /path/to/directory/ /path/to/destination/

    Note: The trailing slash (/) at the end of the source directory is important. If omitted, rsync will create the source directory inside the destination directory.

  • Synchronize files with a remote server:
    rsync -avh /path/to/directory/ user@remote_server:/path/to/destination/
  • Synchronize files from a remote server to the local machine:
    rsync -avh user@remote_server:/path/to/directory/ /local/path/to/destination/

4. Common rsync Options

  • -z: Compresses data during transfer to reduce bandwidth usage.
  • --delete: Deletes files in the destination that are no longer present in the source.
  • -e ssh: Uses SSH for data transfer, ensuring a secure connection.

5. Real-Time Synchronization

If you want to synchronize continuously in real-time, you can use rsync in combination with inotifywait, a command that monitors file system changes.

Basic example:

while inotifywait -r -e modify,create,delete /path/to/directory; do
rsync -avz /path/to/directory/ user@remote_server:/path/to/destination/
done

6. Advanced Usage: Exclusions and Logs

  • Exclude specific files or directories:
    rsync -avh --exclude 'file_or_directory' /path/to/directory/ /path/to/destination/
  • Log the output to a log file:
    rsync -avh /path/to/directory/ /path/to/destination/ --log-file=/path/to/logfile.log

7. Security Considerations

  • Using SSH with rsync: To secure the transfer, it is recommended to use SSH.
    rsync -avh -e ssh /path/to/directory/ user@remote_server:/path/to/destination/

8. Conclusion

rsync is a versatile and powerful tool for synchronizing and copying files on Linux. With this guide, you can start using rsync effectively for various tasks, from local copies to remote synchronization.