vadviktor
7/5/2013 - 8:20 AM

I wish to create a shell script that can place a file change monitor on a specific directory. When file changes occur, then an rsync on that

I wish to create a shell script that can place a file change monitor on a specific directory. When file changes occur, then an rsync on that file/directory will be launched.

This script works, BUT has to be tweaked to behave comfortably. Adding a change buffer, waiting for changes has to be delayed reasonably, etc.

#!/bin/bash
export DISPLAY=:0.0
LOCAL=$1
REMOTE=$2
RSYNC_OPTIONS="-crlHSz --delete --exclude-from $LOCAL/.rsync-filter"

inotifywait -rm -e modify -e moved_to -e moved_from -e move -e create -e delete -e delete_self -e close_write --exclude '\.git|\.subl' --format '%e§#?%w§#?%f' $LOCAL | (
    while true; do
        LINE="";
        read LINE;
        if [ -n "$LINE" ] && [[ $LINE != "" ]]; then
            IFS='§#?' read -a array <<< "$LINE"

            event="${array[0]}"
            directory="${array[3]}"
            file="${array[6]}"
            path="$directory$file"

            echo "`date +'%H:%I:%S'` | $event | $path";

            if [[ $event == 'MOVED_FROM,ISDIR' ]] || [[ $event == 'MOVED_TO,ISDIR' ]] || [[ $event == 'MOVED_FROM' ]]; then
                rsync $RSYNC_OPTIONS $directory $REMOTE
                status=$?
                if [ $status -ne 0 ]; then
                    echo "Rsync error! Return code $status"
                    notify-send -i face-devilish "Rsync ERROR $status" "Failed to $event $directory"
                else
                    echo "Rsync ok. Return code 0"
                    notify-send -i face-angel "Rsync OK" "$event $directory"
                fi
            else
                rsync $RSYNC_OPTIONS $path $REMOTE
                status=$?
                if [ $status -ne 0 ]; then
                    echo "Rsync error! Return code $status"
                    notify-send -i face-devilish "Rsync ERROR $status" "Failed to $event $path"
                else
                    echo "Rsync ok. Return code 0"
                    notify-send -i face-angel "Rsync OK" "$event $path"
                fi
            fi
        fi
    done)