2

I would like to have a trigger and when a particular file is accessed by some process, I would like to be notified (i.e. a script should be run). If I understand correctly, this could be achieved with inotify.

If I have a file /foo/bar.txt how would I set up inotify to monitor that file?

I am using Debian Wheezy with kernel 3.12 (my kernel has inotify support)

3

According to Gilles on Super User:

Simple, using inotifywait (install your distribution's inotify-tools package):

while inotifywait -e close_write myfile.py; do ./myfile.py; done

This has a big limitation: if some program replaces myfile.py with a different file, rather than writing to the existing myfile, inotifywait will die. Most editors work that way.

To overcome this limitation, use inotifywait on the directory:

while true; do
  change=$(inotifywait -e close_write,moved_to,create .)
  change=${change#./ * }
  if [ "$change" = "myfile.py" ]; then ./myfile.py; fi
done
  • 1
    “It's simple but has two important issues: Events may be missed (all events in the loop) and initialization of inotifywait is done each time which makes this solution slower for large recursive folders.” – Wernight (Fixing that post is on my todo list. Don't hold your breath.) – Gilles 'SO- stop being evil' Jun 6 '14 at 2:08
2

The basic shell interface to inotify is inotifywait from inotify-tools.

To monitor all accesses to a file:

inotifywait -mq --format '%e' /path/to/file |
while IFS= read -r events; do
  /path/to/script "$events"
done

Your script is called with a comma-separated list of simultaneous events, each time something happens to the file (read, write, close, …).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.