3

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)

2 Answers 2

4

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
  • 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.) Commented Jun 6, 2014 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, …).

1
  • Same limitation applies here : editors like VIM replace the file with a different file. In monitor mode, inotifywait will not die silently but detect MOVE_SELF, then ATTRIB, then DELETE_SELF events on the first edit, then nothing on the subsequent edits. Commented Sep 27, 2021 at 17:21

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.