12

I wonder if I can write a script that will monitor for a change in a file and execute some action when the change is detected.

Detailed explanation:

  1. OpenVPN writes its status to a file every 1 minute.
  2. I need to parse this status file and take action.
  3. OpenVPN truncates the status file before writing to it.
  4. I tried writing to a named pipe, but I get undesirable (but not fatal) errors in the app when it fails to truncate the pipe.
davidparks21
  • 928
  • 1
  • 12
  • 27
  • In case the modification is actually *appending* to the file, hanging on `tail -f` is probably the easiest way. But only for appending. – SF. Jul 05 '11 at 14:35

5 Answers5

21

Cheap n' dirty way:

Loop stat -c %Y file and take action when the modification time changes.

Probably better:

Use the inotify cron service to watch for file modification events and run your action:

/path/to/your/file IN_MODIFY /path/to/your/script $#
Cakemox
  • 25,209
  • 6
  • 44
  • 67
4

Take a look at incron[1] or other inotify-stuff to trigger the execution of your script.

[1] http://inotify.aiken.cz/?section=incron&page=about&lang=en

m.sr
  • 1,060
  • 1
  • 8
  • 19
2

inotify would be the right way to do it. Tutorials are given in some LinuxForYou magazine edition for this very question.

1

Quick and dirty way :

function wait_file_changed {
    tail -fn0 "$1" | head -n1
}

wait_file_changed /tmp/potato
0

So have a script that:

1) Checks the modification time on the file (with stat)
2) If the modification time is newer than when last checked, it has changed
3) Parse it and perform your action
4) Else sleep for 1 minute and then reloop

Rafiq Maniar
  • 1,120
  • 9
  • 15