Search code examples
bashsshinotifywait

Script for directory mirroring with inotifywait and ssh


I have a script that try to mirror a specific directory from a local server to a remote one. It looks like that:

inotifywait -mr --format '%w%f' -e close_write -e moved_to -e delete /mydir | \
while read FILECHANGE
do
    if [ -f $FILECHANGE ]
    then
        rsync --bwlimit=4096 --progress --relative -vrae 'ssh -p 22' $FILECHANGE $REMOTEHOST:/
    else
        ssh -p 22 $REMOTEHOST "rm $FILECHANGE"
    fi
done

In case of multiple create of files, as for example a touch command: touch 1 2 3 The 3 files are well transfered.

But if I delete several files at once: rm -f 1 2 3 Only the first 1 is deleted.

If I replace the ssh command by just an echo $FILECHANGE, the 3 files are well displayed in the console. So it seems the problem come from the ssh command, but I can't explain why and solve it.

Anyone as an idea?


Solution

  • Well, I found the issue: it seems that the ssh command was eating the output of the inotifywait command when run. So, to prevent that, I add the 0<&- redirection after the ssh, to close the stdin.

    inotifywait -mr --format '%w%f' -e close_write -e moved_to -e delete /mydir | \
    while read FILECHANGE
    do
        if [ -f $FILECHANGE ]
        then
            rsync --bwlimit=4096 --progress --relative -vrae 'ssh -p 22' $FILECHANGE $REMOTEHOST:/
        else
            ssh -p 22 $REMOTEHOST "rm $FILECHANGE" 0<&-
        fi
    done
    

    Now it works.