Linux – How to automatically run a script when the contents of a directory changes in Linux

inotifylinuxscripting

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?

Best Answer

If you're lucky enough to be on a debian-based distribution, apt-get install dnotify. Other distributions probably have something similar - look for the dnotify name.

dnotify is a simple program based on Linux kernel 2.4.19+'s dnotify API. dnotify can execute a specified command each time the content of a specific directory changes. It is run from the command line and takes two arguments: one or more directories to monitor and a command to execute whenever a directory has changed. Options control what events to trigger on: when a file was read in the directory, when one was created, deleted and so on.

If you want to handle this within your own program, dnotify is also the API you want to use.