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-toolsHere is one example script which utilizes inotifywait:
#!/bin/shwatch_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 ;; esacdoneGive 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
No comments:
Post a Comment