Launching actions on file or directory events using incron


The incron service is working in a similar way than the cron daemon. The difference is that you can use incron to monitor files or directories and launch specific actions on different events (for example if a new file is created or a file is saved).

A practical example:

You could use incron to restart your webserver automatically as soon as you modify/save its configuration file. If /etc/apache2/apache2.conf for example is saved you’d execute /etc/init.d/apache2 force-reload

Installation on debian-based distrubutions (Debian >= Lenny, Ubuntu and others) you can install it easily by executing:

apt-get install incron

Installation onĀ  Fedora, CentOS or RedHat:

yum install incron

Permissions:

By default, no existing user is allowed to use incron. To give this permission to specific users, you have to edit the files:

/etc/incron.allow

/etc/incron.deny

Similarily to cron (crontab) theres the command incrontab.

incrontab -l will list the current entries

incrontab -e will open the current incrontab for editing

ATTENTION! You have to allow users (also root) to use incron, else you’ll just have an error message in your logs. To do so you just enter the username in the file /etc/incron.allow.

Updating incrontab:

With incrontab -e You can bind actions to specific events on directories or files.

To stay with the example mentionned above:

/etc/apache2/ IN_CLOSE_WRITE /etc/init.d/apache2 reload

You can enter directory paths or files as well.

The syntax is always: File/Directory Event Command

In this example, the webserver will be restartet as soon as we edit & save something in /etc/apache2/.

The list of available events:

IN_ACCESS When the file is read
IN_ATTRIB When permissions or other file attributes are changed.
IN_CLOSE_WRITE When a file is opened for writing and saved.
IN_CLOSE_NOWRITE When a file was opened for reading and then is closed.
IN_CREATE When a new file is created in the directory that we monitor
IN_DELETE When a file is deleted in the directory that we monitor
IN_DELETE_SELF When the directory or the file itself is deleted.
IN_MODIFY When the file or directory is modified.
IN_MOVE_SELF When the file or directory is moved.
IN_MOVED_FROM

When the file or directory is moved from the directory that we monitor
IN_MOVED_TO When a directory or file is moved into the directory that we monitor
IN_OPEN When a file is opened

Test:

Depending on your system editor (normally vi or nano), you can save end quit after having entered your incrontab entry.

As soon as you save something within /etc/apache2/ you should have log entries in /var/log/syslog or /var/log/messages depending on your system environment. Example:

Mar 29 12:34:39 h1643630 incrond[21786]: (root) CMD (/etc/init.d/apache2 reload)