2

I'm looking for a way to monitor a file and trigger an event as soon the file was removed. Once it is removed I will replace/copy a new file and start the monitor again.

E.g.

watch "/tmp/fileToMonitor.txt"

// file deleted by some process
cp new_file "/tmp/fileToMonitor.tx"

// watch file again (repeat same steps..)

How can I do that with a bash script? Is this possible?

  • There's auditd. Do some research on it. – Larssend Jul 12 '15 at 16:29
  • Also research inotify – cybernard Jul 12 '15 at 16:47
4

You can do this with inotifywait utility (from inotify-tools package, under Debian at least).

inotifywait can take event names as arguments and wait for them to happen on monitored file or directory, before returning. In your case, you would need to use the delete_self event, to indicate that you want the program to return when monitored file is deleted.

So to copy a new file as soon as /tmp/fileToMonitor.txt is removed, you would do:

inotifywait -e delete_self "/tmp/fileToMonitor.txt" && cp new_file "/tmp/fileToMonitor.txt"

If you want to start monitoring again, you could put this inside a loop:

while true ; do
  inotifywait -e delete_self "/tmp/fileToMonitor.txt" \
    && cp new_file "/tmp/fileToMonitor.txt"
done
  • Great. Thank you. Exactly what I was looking for. – user797717 Jul 12 '15 at 17:24
  • You're welcome :) The modify event is very handy to recompile your files on change, by the way. In general this is what I use this tool for. – Qeole Jul 12 '15 at 17:34

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.