7
Sep

Script to Watch for Changes to Disk and Run Script Immediately

By utilizing inotifywait from the inotify-tools package, we can monitor changes to disk and immediately run a script or command on that file. No need for a cron job here…

To install inotify-tools, we simply use apt-get (or yum, depending on your distro):

sudo apt-get install inotify-tools

Here is one example script which utilizes inotifywait:

#!/bin/sh

watch_dir="/media/md0/"
inotifywait -mr -e create -e delete -e modify --timefmt '%Y-%m-%dT%H%M%S' --format '%w;%f;%e;%T' "$watch_dir" | while IFS=';' read -r DIR FILE EVENT TIME; do

  echo "${EVENT} ${TIME}: ${DIR}${FILE} >> /home/user/watched

  case "$EVENT" in
    "CREATE"|"MODIFY")
      echo "Run create/modify script on file: ${DIR}${FILE}" >> /home/user/watched
      ;;
    "DELETE")
      echo "Run delete script on file: ${DIR}${FILE}" >> /home/user/watched
      ;;
  esac
done

Give your script a name, executable rights, and run it in the background. For example:
chmod +x myscript.sh && ./myscript.sh &

Obviously, you’ll need to modify the script to fit your needs, but this should give you a jump start on your project.

Note: There’s an infinite loop bug in the script above. Remove the ‘modify’ options and this will clear things up. However, if you do that, then you’re really only looking for file creation or deletion. You could add more conditionals to the script above to prevent the loop. If anybody has a suggestion, I’d be happy to update the script.

Take this a step further by following my guide on Automatically Start a Script at Linux Bootup

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 0 Comment So Far

Share your thoughts, leave a comment!