How do I run a script when a file is created in a certain directory?
2 Answers
You could use incron (inotify cron).
Same idea as cron
, except that instead of being time-based, you define an incrontab
that specifies what command to run upon some given event in the filesystem.
The incrontab
in your case would look like:
/tmp IN_CLOSE_WRITE /path/to/someCommand $#
And someCommand
would be called whenever a file has been written and closed with the filename as argument (and someCommand
would need to check if it's been passed a file called myFile
).
A note of warning though. /tmp
is world writable, so anybody and anything can write files there and can also create symlinks there. So it can cause you to overwrite any file you have write access to when you transfer that myFile
(using a symlink), or it can cause you to run another command than the one you expect (like a trojan). It would make more sense to put the file in a directory where only you have write access to.

- 544,893
You can put same script in cron
:
while true; do
modification_time=`stat --printf=%y /tmp/mydir`
if [ "$modification_time" != "`stat --printf=%y /tmp/mydir`" ]; then
echo YOUR DIR CHANGED
fi;
done;
I tested work.
You can just change echo line
.

- 10,850