Linux: Constantly rsync two directories.

Assume you have two directories that needs to be constantly synced, not just every one minute by using a cronjob but as soon as possible…

Linux: Constantly rsync two directories.
Photo by KOBU Agency on Unsplash

Assume you have two directories that needs to be constantly synced, not just every one minute by using a cronjob but as soon as possible, how we can achieve this? using inotify!

Install inotify$ sudo apt-get install inotify-tools

Inotify watch for changes in files and/or directories and then can trigger other actions, like rsync in our case.

Create the watcher script

Create the following script as watcher1.sh and make it executable#!/bin/bash
while inotifywait -r -e modify,create,delete,move /my/path_to/src; do
   rsync -avz /my/path_to/src/ /my/path_to/dst --delete-after
done

Explain the parameters

  • /my/path_to/src: The source directory we want to constantly sync.
  • /my/path_to/dst: The destination directory.
  • while inotifywait: A loop which waits until an event of modify, create, delete or move happens.
  • rsync: if inotify is triggered by an event rsync will run and will do any changes from src to dst.
  • — delete-after: This is really important! if you omit this parameter any deletion in src will not be replicated to dst.

I hope you found this article useful :)