Rsync (remote sync) is a linux utility to synchronize local and remote files and directories, mainly used in terminal.
I use this mainly in downloading/uploading files and directories from and to remote servers or even local files. I use rsync as well with shell scripts for backups that are ran automatically daily using the crontab utility.
Basic syntax
It's straight forward to remember and you can sync either directory to directory within the local environment, or local to remote or remote to local. One thing to note is to add the trailing slash on the source directory to sync the contents of the directory instead of the directory itself.
rsync [option] [source]/ [destination]
rsync [option] [source]/ [user@][host]:[destination]
rsync [option] [user@][host]:[source]/ [destination]
Common options
Some common options I use with rsync:
- -a for archive mode, which is the same -rlptgoD (no -H) options
- -p to show progress during transfer
- -u for update and skip files that are newer on the destination
- -n for dry run, especially to test before transferring.
- --exclude to exclude files or directories matching the pattern
- --delete to delete the files from the destination (Note: be careful in using this, make sure to use -n to test what you will delete on the destination)
Exclude certain files
rsync -aPun [source]/ [destination] --exclude="*.txt" --delete
Include only image extensions
rsync -aP [source]/ [destination] --include="*/" --include="*.gif" --include="*.jpeg" --include="*.jpg" --include="*.png" --exclude="*"
Rsync with SSH key file
Sometimes servers uses an ssh key file instead of using a username. You can use your key file by using the -e for specifying the remote shell and passing the key file to use that's on your local environment.
rsync -aP -e "ssh -i [~/path/to/keyfile]" [user@][host]:[source]/ [destination]
Rsync with a different port
Use a different port to connect.
rsync -aP -e "ssh -p [port]" [user@][host]:[source]/ [destination]
Rsync using sudo at the destination
Use sudo at the destination server.
rsync -aP -e "ssh" --rsync-path="sudo rsync" [user@][host]:[source]/ [destination]
Add new comment