RSS

Inotify

Inotify (inode notify) is a Linux kernel subsystem that acts to extend filesystems to notice changes to the filesystem, and report those changes to applications. Therefore Inotify libraries are available for all major programming and scripting languages.

But when it comes to the Inotify tools for the shell people tend to think like a programmer missing object oriented features and not like a shell user. This can be seen very nicely on the vastness of shell script examples using the Inotify tools within infinite loops.

#!/bin/bash
while true; do
    inotifywait -e create /some/path/to/  && \
    ./do_something.sh
done

The shell is no object oriented programming language, but it's big on daemons, background processes and the pipe. Yet another drawback of the above example: The script do_something.sh has to contain a loop to find the created file(s). Thus instead of permanently setting up the Inotify watch and dismissing it after an event, one can use the monitor flag of inotifywait in order to allow it to run permanently:

inotifywait -c -m -r -e create /some/path/to/ | ./do_something.sh

 In this case our new do_something.sh script has to be able to read multiple lines from the pipe. Otherwise the entire construct will quit after the first event. Thus we simply need a loop in our script to read those multiple lines and parse the output of inotifywait, e.g. with such a script:

#!/bin/bash

while read indata
do
    indir=$(echo "$indata" | cut -d"," -f1)
    infile=$(echo "$indata" | cut -d"," -f3)
    outfile="/some/other/path/$infile"
    change_infile.sh $infile && mv $infile $outfile
done

References

  1. http://en.wikipedia.org/wiki/Inotify
  2. http://en.wikipedia.org/wiki/Pipeline_(Unix)
  3. http://blog.lagentz.com/general/automate-your-shell-scripts-using-inotify-and-inotifywait/
  4. http://www.daniweb.com/software-development/shell-scripting/threads/380711/read-from-pipe-waiting-until-data-is-fed-into-pipe#post1640490
  5. http://www.thegeekstuff.com/2010/04/inotify-c-program-example/