métier

How to execute a command when a file change ?

Publié par Éric Le Merdy

Use incron ! It is similar to cron that triggers commands based on time. Incontab triggers commands based on file system changes.

1. Install incron

sudo apt-get install incron

2. List your incron jobs

incrontab -l

returns :

user 'ericlemerdy' is not allowed to use incron

3. Authorize your user to have incron job

sudo whoami >> /etc/incron.allow

4. List your incron jobs

incrontab -l

returns :

no table for ericlemerdy

5. Add a job to your incron

incron -e

Your text editor is now opened, ready to add your first job.

6. Help on job syntax

man 5 incron

The syntax is :

<path> <mask> <command>

Incron will examine your <path> based on the <mask> that can be IN_ACCESS or IN_MODIFY for exemple and then executes your <command>.
Exemple :

/home/ericlemerdy/tutorial.txt IN_MODIFY pandoc -s --webtex -i -t slidy $@ -o /home/ericlemerdy/tutorial.html

This jobs inspects the file /home/ericlemerdy/tutorial.txt. Every time the file is modified (according to the IN_MODIFY mask), a documentation is generated through a command.
Note the use of $@ in the command. This is replaced with the examined path.

7. Tracking job execution

You can follow the incron activity through the syslog:

tail -f /var/log/syslog

You should get :

Feb 25 17:29:36 harukiya incrond[21714]: starting service (version 0.5.9, built on May 10 2010 14:59:40)
Feb 25 17:29:36 harukiya incrond[21715]: loading system tables
Feb 25 17:29:36 harukiya incrond[21715]: loading user tables
Feb 25 17:29:36 harukiya incrond[21715]: ready to process filesystem events
Feb 25 17:59:49 harukiya incrond[21715]: table for user ericlemerdy created, loading
Feb 25 18:01:23 harukiya incrond[21715]: (ericlemerdy) CMD (pandoc -s --webtex -i -t slidy /home/ericlemerdy/tutorial.txt -o /home/ericlemerdy/tutorial.html)

Conclusion

Incron can be very helpful to execute your tests when your code change or generate a webpage when the sources are changing.