natjohan's blog

Posted dim. 09 juin 2013

Tip of the week 19

Monitor file changes to trigger an action


According to the man incron is an "inotify cron" system. It consists of a daemon and a table manipulator. You can use it a similar way as the regular cron. The difference is that the inotify cron handles filesystem events rather than time periods.


Just install the following package with your favorite package installer (yum for Fedora, aptitude for Debian/ubuntu, pacman or yaourt for archlinux)

natjohan# yum install incron
natjohan# rpm -ql incron


Main files are :
  • /etc/incron.conf : main incron configuration file
  • /etc/incron.allow : contains users allowed to use incron, you have to create it

At first you have to create /etc/incron.allow , for example (to allow root to use incron)


The incron syntax is

<file | directory> <event> <command> <options>

Events are 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 (*)

There is som wildcard you can use in your command

$$ dollar sign
$@ watched filesystem path (see above)
$# event-related file name
$% event flags (textually)
$& event flags (numerically)

Now you can chose a file to trigger (here, we just want to restart the freeradius service when the user file changes), and add an entry in your incron with

natjohan# incrontab -e

/etc/freeradius/users IN_CLOSE_WRITE, NO_LOOP /etc/init.d/freeradius restart

natjohan# incrontab -l
/etc/freeradius/users IN_CLOSE_WRITE, NO_LOOP /etc/init.d/freeradius restart

Note : On Fedora 18, if you don't have vim installed, the incrontab -e output an error message editor finished with error: No such file or directory which mean you just have to edit /etc/incron.conf with editor = vi in or install vim


Just open another terminal and you can show incron commands with

natjohan# tail -f /var/log/syslog
natjohan# tail -f /var/log/cron
(it depends on your system)

Jun 09 23:21:46 srv incrond[17290]: (root) CMD (/etc/init.d/freeradius restart)


Incron does not allow to monitor a file several times (one line per file/folder only), so if you want to launch many commands, the cleanest way to do it is to create a bash file with your commands.

natjohan# incrontab -e

/etc/freeradius/users IN_CLOSE_WRITE, NO_LOOP myscript

Go further

official website
Category: ToTW
Tags: linux incron inotify file