Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a bash script automatically when directory contents chage

My goal is to run a bash script automatically whenever any new file is added to a particular directory or any subdirectory of that particular directory.

Detail Scenario:

I am creating an automated process for file submission from teachers to students and vice versa. Sender will upload file and it will be stored inside the Uploads directory in the LAMP server in the format, ex. "name_course-name_filename.pdf". I want some method so that when any file stored inside the Uploads folder, the same time a script will be called and send that file to the list of receives. From the database I can find the list of receiver for that particular course and student.

The only concern of mine is, how to call a script automatically and make it work on individual file whenever the content of the directory changes. Cron will do in intervals but not a real time work.

like image 732
pali Avatar asked Jun 13 '13 11:06

pali


1 Answers

Linux provides a nice mechanism for that purpose which is called inotify. inotify is mostly available as a C API. But there have been developed shell utilities as well. You should use inotifywait from inotifytools (pkg name in debian) for this. Here comes a basic example:

#!/bin/bash

directory="/tmp"   # or whatever you are interested in

inotifywait -m -e create "$directory" |
while read folder eventlist eventfile
do
    echo "the following events happened in folder $folder:"
    echo "$eventlist $eventfile"
done

Update:

If the problem goes complicated, for example you'll have to monitor recursive, dynamic directory structures, you should have a look at incron It's a cron like daemon which executes scripts on certain events. But the events are file system events rather than timer events.

like image 133
hek2mgl Avatar answered Sep 27 '22 19:09

hek2mgl