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.
  • 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 5 '11 at 14:35
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 $#
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

2

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

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

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.