inotify script stops after first change

Posted on

Problem :

Inspired by this superuser answer I have written the following copy_library.sh script, saved in the same folder as a file called library.bib:

#!/bin/sh
while inotifywait -e close_write library.bib; do
    cp -f ./library.bib ../other_place/ ;
    echo "Library copied"
done

If I start this script manually with ./copy_library.sh the process exits after the first copy (which works successfully):

londonrob ~/mydir
> ./copy_library.sh 
Setting up watches.
Watches established.
library.bib CLOSE_WRITE,CLOSE 
Library copied
Setting up watches.
Watches established.
londonrob ~/mydir
>

and no further changes are tracked. I’m sure I’m supposed to do something with this script so it’s running continuously “in the background” without me having to start it manually.

But what?

Solution :

From the inotifywait man page:

inotifywait efficiently waits for changes to files using Linux’s
inotify(7) interface. It is suitable for waiting for changes to files
from shell scripts. It can either exit once an event occurs, or
continually execute and output events as they occur.

and

-m, –monitor
Instead of exiting after receiving a single event, execute indefinitely. The default behaviour is to exit after the first event
occurs.

EDIT: I have a log, which is appended to each 15 seconds. The following script executes the while one loop for each line outputted by inotifyread:

#!/bin/sh

inotifywait -e modify /tmp/modem_log.csv -m | while read line; do
    echo "$line"
    echo "Copy coperation here..."
done

In your case, you have to change the event (modify) to close_write, of course.

Leave a Reply

Your email address will not be published. Required fields are marked *