RSync

Updated on 03 Oct 2020

Here are some additional resources to help us with using rsync.

Copy file / directory from local to local

In your home directory, the following command will copy the Downloads/mama.txt file to your test/ directory.

rsync -avz Downloads/mama.txt test/

Where

  • a archive mode (perserves file permissions, timestamps etc)
  • v verbose (provide extra console output)
  • z compress mode, compress the file(s) and decompress at the location.

Copy file / directory from local to server

Similar to the example above, except that this time I am specifying the server (and location) for the file. The location is simply the home directory on the remote server, but it can be any location you have access to.

rsync -avz mama.txt username@remote_server:/home/username/

In this particular example I am being asked for a password. If I had created a SSH key and shared that with the other machine, then I would not be prompted for the password.

Exclude files / directories

I can copy entire directories, and with that chose to exclude certain file types or directories using the --exclude flag. If you have multiple items to exclude, just repeat the --exclude option for each one.

rsync -avz /home/username/ username@remote_server:/home/username/ --exclude deploy --exclude *.gz --exclude tests

Delete destination files

There is an option to remove files on the destination machine that don’t exist on the source using the --delete flag. This is a scenario where you might want to sync two machines.

rsync -avz forCopy/ usernanme@remote_server:/home/username/forCopy/ --delete

Delete source files

It could be that once a file is copied to a remote machine, you no longer need it on the source machine. In that case, --remove-source-files option will work for you.

rsync -avz forCopy/mama.txt username@remote_server:/home/username/forCopy/ --remove-source-files

Dry run

If you’re not sure of how the rsync will work, you can use --dry-run to test your configuration.

rsync -avz forCopy/ username@remote_server:/home/username/forCopy/ --delete --dry-run

This will give you the exact output you’d be expecting without actually performing the task. Once you’re confident that you’ve got your command correct, you can remove the --dry-run and rsync will run for real.