How to Sync Two Folders with Command Line Tools – Folder Synchronization Methods

file-copyfileslinuxsynchronization

Having migrated to Linux from Windows, I would like to find an alternative software to Winmerge or rather learn command line tools to compare and sync two folders on Linux. I would be grateful if you could tell me how to do the following tasks on the command line… (I have studied diff and rsync, but I still need some help.)

We have two folders: "/home/user/A" and "/home/user/B"

Folder A is the place where regular files and folders are saved and folder B is a backup folder that serves as a complete mirror of folder A. (Nothing is directly saved or modified by the user in folder B.)

My questions are:

  • How to list files that exist only in folder B? (E.g. the ones deleted from folder A since the last synchronization.)

  • How to copy files that exist in only folder B back into folder A?

  • How to list files that exist in both folders but have different timestamps or sizes? (The ones that have been modified in folder A since last synronization. I would like to avoid using checksums, because there are tens of thousands of files and it'd make the process too slow.)

  • How to make an exact copy of folder A into folder B? I mean, copy everything from folder A into folder B that exists only in folder A and delete everything from folder B that exists only in folder B, but without touching the files that are the same in both folders.

Best Answer

This puts folder A into folder B:

rsync -avu --delete "/home/user/A" "/home/user/B"  

If you want the contents of folders A and B to be the same, put /home/user/A/ (with the slash) as the source. This takes not the folder A but all of it's content and puts it into folder B. Like this:

rsync -avu --delete "/home/user/A/" "/home/user/B"
  • -a Do the sync preserving all filesystem attributes
  • -v run verbosely
  • -u only copy files with a newer modification time (or size difference if the times are equal)
  • --delete delete the files in target folder that do not exist in the source

Manpage: https://download.samba.org/pub/rsync/rsync.html

Related Question