Restart process on file change in Linux

Yes, you can watch a directory via the inotify system using inotifywait or inotifywatch from the inotify-tools.

inotifywait will exit upon detecting an event. Pass option -r to watch directories recursively. Example: inotifywait -r mydirectory.

You can also specify the event to watch for instead of watching all events. To wait only for file or directory content changes use option -e modify.


This is an improvement on the answer provided in the question. When one interrupts the script, the run process should be killed.

#!/bin/sh

sigint_handler()
{
  kill $PID
  exit
}

trap sigint_handler SIGINT

while true; do
  $@ &
  PID=$!
  inotifywait -e modify -e move -e create -e delete -e attrib -r `pwd`
  kill $PID
done

Tags:

Linux

Shell