Triggering Commands on File/Directory Changes in Ubuntu
He we will introduce a new linux tool called Incron. It is similar to cron, but instead of running commands based on time, it can trigger commands when file or directory events occur. First of all, install incron using the command
sudo apt-get install incron
Before starting to use incrontab, we must give permissions for a user to use the service. To do this do:
nano /etc/incron.allow
and add the desired username to it.
Using incron is very much like using cron, ie. you can list, edit, and remove incrontab entries by using -l, -e and -r options, respectively. Have a look at the man page (man incrontab) for more options and the directions for usage.
man 5 incrontab will show the format of the crontabs we are going to create. Basically it is as follows:
path mask command
where path> can be a directory or a file that is watched. path> can be one of the following:
| IN_ACCESS | File was accessed (read) (*) |
| IN_ATTRIB | Metadata changed (permissions, timestamps, extended attributes, etc.) (*) |
| IN_CLOSE_WRITE | File opened for writing was closed (*) |
| IN_CLOSE_NOWRITE | File not opened for writing was closed (*) |
| IN_CREATE | File/directory created in watched directory (*) |
| IN_DELETE | File/directory deleted from watched directory (*) |
| IN_DELETE_SELF | Watched file/directory was itself deleted |
| IN_MODIFY | File was modified (*) |
| IN_MOVE_SELF | Watched file/directory was itself moved |
| IN_MOVED_FROM | File moved out of watched directory (*) |
| IN_MOVED_TO | File moved into watched directory (*) |
| IN_OPEN | File was opened (*) |
When monitoring a directory, the events marked with an asterisk (*) above can occur for files in the directory, in which case the name field in the returned event data identifies the name of the file within the directory.
Let’s create our first incron job. We’d like to monitor the directory /home/Downloads, and whenever a pdf file is downloaded into it, we want incron to activate a script that moves the file to another location. This is how we do it:
incrontab -e and put the following text into it.
/home/Downloads IN_CREATE /home/xxxx/.mvpdf.sh
Once the file is saved, type incrontab -l to see a list of incron jobs.
Test if everything is working as intended.








