I want to automatically run a script whenever new files are copied into a particular directory. In other words, is there a way in Linux to "watch" a directory for changes and then run something in response to the change?
|
|
If you're lucky enough to be on a debian-based distribution,
If you want to handle this within your own program, dnotify is also the API you want to use. |
|||||||||||||||||||||
|
|
You can run a script with the inotify-tools, something like this. It will watch the directory for changes in modified files, new files, and deleted files, then it will execute the script.
|
|||||||||
|
|
incron is basically what you want, I think. It uses inotify as the notification mechanism (which, as others have pointed out, supercedes dnotify), but doesn't require a script that continuously runs, using inotifywait or similar (although, obviously, the incron daemon is running all the time). System-wide 'crontabs' and user 'crontabs' are supported in a similar way to standard cron, but rather than specifying times as triggers, inotify events and files/directory names are used. incron is packaged for many distributions, including Ubuntu and Debian, I believe. |
|||
|
|
|
There's a piece of software solely for this purpose, autoenv You might want to check it. |
|||
|
|
|
entr is the simplest and most composable file notification tool I have seen. Its use is optimized toward watching files rather than directories, but it can also solve your case. To detect and act on the added file, combine it with other tools like e.g. To check for added files in a directory:
If you want to also act when an existing file changes:
... and that's where the loop mechanism comes in handy, as the If you want better error handling and want to make sure things only run once per added/removed file, things get a bit quirky, but for these simple cases it's brilliant. EDIT: If you want to do this on a system level, something like incron, just add the script to your favorite process manager (like s6, runit, systemd or sysvinit and skip the loop:
The |
||||
|
|