Quick bash script using inotify and rsync to one-way mirror directories
I needed a way to mirror a directory between to shared nothing servers. I started out uing cron to fire off rsync, but the application required the files be synched "immediately".
Enter inotify. I installed the inototify-tools go get a shell interface to filesystem events from the kernal. A couple lines of shell script later and we have a daemon like utility which waits for relevant events and rsyncs the required minimum files.
Run like so:
nohup sync.sh /full/path/to/dir user@host & > /dev/null 2>&1
After I wrote this I found a couple other scripts and programs which do the same or similar things, but this one is pretty minimal and I like that.
- http://code.google.com/p/lsyncd/
- http://ebalaskas.gr/blog/?page=PIrsyncD
- http://www.linuxawy.org/node/13
#!/bin/sh
set -e
set -u
BASEDIR="$1"
REMOTE_HOST="$2"
RSYNC="rsync -av -e ssh --delete "
# Initial sync
$RSYNC ${BASEDIR}/* ${REMOTE_HOST}:${BASEDIR}/
# Wait for individual file events and keep in sync
inotifywait --format '%e %w' -e close_write -e move -e create -e delete -qmr $BASEDIR | while read EVENT DIR
do
# Fork off rsync proc to do sync
$RSYNC ${DIR}/* ${REMOTE_HOST}:${DIR}/ &
done