Last week I worked on an old project and needed to synchronize two folders (let say web resources and deployment folder). Originally the project was using ruby tooling to do that but seems it is old enough now to require to rewrite it.

I assumed at that moment that bash will be more reliable than ruby for the project and therefore replaced the small Guardfile by a plain script!

Idea is to rely on inotify and just loop over its events to synchronize the folders. There are a tons of ways to do it but here is the raw idea:

#! /bin/bash

from=src/main/webapp/js
to=target/apache-tomee/webapps/sample/js

while inotifywait -r -e modify,create,delete $from; do
    sleep 1
    cp -r $from/* $to
done

Nothing crazy but a few points to note:

  • depending your editor/IDE you need this sleep 1 pause to avoid to capture the temporary file(s) changes instead of the actual file changes (same happens using java watch service under linux)
  • the plain copy (cp) can be replaced with a rsync which would be more optimized than a cp
  • depending what you do you can remove the delete event from the ones watched on inotifywait command

And here we are! Make this script executable (chmod +x script.sh), run it and your folders will stay synchronized and any change to $from will be copied to $to!

From the same author:

In the same category: