Update the remote only if there is a newer version is on the local filesystem:
If we want to copy files over the remote-host that have been updated more recently on the local filesystem. It is done with –update flag. The behavior is now like this:
- Files that do not exist on the remote-host are copied.
- Files that exist on both local and remote but have a newer timestamp on the local-host are copied to remote-host. (Conversely, files that have an older timestamp are not copied).
Here, I made some changes in file1 and file2, but the changes in file2 were done recently. So only file2 will get synced.
rsync -avhe ssh --progress --update /foo root@remote-host:/tmp/
Output:
Automatically delete files from local-host after successful transferring
Now, suppose we have a web server and a backup server and we created a daily backup and synced it with our backup server and then we don’t want to keep the local copy of the backup in our web server. So, instead of deleting it manually after successful transfer, we can use the --remove-source-files
flag to automatically delete the files from the web server.
rsync -avhe ssh --remove-source-files /foo user@backup-server:/tmp
Output:
Note: This will delete only the files and not the directories.
Delete the files that have been deleted on the local-host
If there are some files that are deleted on the local-host and we want that to be updated on the remote host as well, then we need to use the --delete
option.
rsync -avhe ssh /foo --delete user@remote-host:/tmp/
Output:
So, here file1, file2, file3 were deleted on the local-host, and as can be seen, are updated in the remote-host as well.
Note: `rsync` does not delete the files automatically to sync the directories present on both sides.
Performing a Dry run with `rsync`
A Dry run makes `rsync` perform a trial run that doesn’t make any changes and displays almost the same output as a real run would do. It is generally used with the -v, –verbose and/or -i, –itemize-changes options so as to see what a `rsync` command would do before one actually runs it.
rsync -avhe ssh --dry-run --chown=USER:GROUP /foo user@remote-host:/
Output:
Conclusion
In this article we discussed the rsync command in Linux which is a versatile and powerful tool for synchronizing files and directories between hosts or machines. With its delta-transfer algorithm and various options, it offers efficient data synchronization, backup capabilities, and file transfer management. By mastering the rsync command, Linux users can ensure file consistency, optimize data transmission, and streamline their data management workflows.