Every once in a while I need to get two folders synchronised. In the past I used a synchronisation app to get this done, but somewhere along the way of macOS system updates, it stopped working and I never bothered to get another one.
This week, I needed to synch folders again and while there are a few apps like that on the App Store, the few times I need it, don’t rectify buying one. I wanted to find a way to do it via the command line.
I started looking into it and first tried rsync to get the job done. Since rsync is a “uni-directional mirroring utility” it would have required two passes to get both directories in sync. While researching on how to possible get this done the easy way, I discovered Unison, which sounded exactly like what I was looking for.
Unison is a file-synchronization tool for OSX, Unix, and Windows. It allows two replicas of a collection of files and directories to be stored on different hosts (or different disks on the same host), modified separately, and then brought up to date by propagating the changes in each replica to the other.
Unison is free and available as a GUI app for different platforms or as a command line tool. I opted for the latter, which can be installed on macOS via Homebrew by running this command in the Terminal.app:
brew install unison
Once installed, Unison is ready to go and doesn‘t require much learning. For my task at hand it was as simple as this command:
unison /path/to/dir1 /path/to/dir2
This command without any arguments requires you to confirm every file to be synched (by pressing f) before it eventually starts to copy the files.
After confirming the above with
y Unison starts to copy and displays the result like this:
After trying it out a few times and reading through the rather comprehensive documentation, I eventually settled with the following command:
unison /path/to/dir1 /path/to/dir2 -batch -times
-batch option does not ask any questions at all, which is more convenient if there are a lot of files. Be sure to know what you are doing in this case ;)
-times option synchronises the modification times, otherwise the file modification dates will show the time they have been synched with Unison.
I’m really happy I found Unison and will soon try this on some larger directories, e.g. synchronising a whole hard drive to create a duplicate for backup.