Linux – Trigger commands and tasks during file system changes

In this tutorial, we will be showing you how to run tasks/scripts when the file system creates an event.


We will be doing this something called incrontab, as the name suggests it is similar to crontab

You may be wondering what a filesystem event is and why this is useful, let me explain.

So when a file is created/modified/deleted/opened it will send a signal to the OS but as we don’t usually have anything installed to capture these events they go unnoticed.

in my experience this is useful for following things:

  • You want to email someone edits a file
  • You are using an SFTP server you want to move the file
  • You want to restart a service as soon as a config file has been edited.


Log into your Linux box then run:


sudo apt install incron

Centos/Red Hat/Amazon Linux:

sudo yum install incron

Setting Up

Once this is installed we can run the following:

incrontab -e

Below is the structure of the command you will need to place inside incrontab -e

<path> <mask> <command>
  • <path> is file/folder you are getting incron to monitor for changes
  •  <mask> is the event incron should be looking for
  • <command> this is the command that you want to run.

Incron has quite a few events they are quite self-explanatory:

  • 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 are also variables you can use:

  • $$   dollar sign
  • $@   watched filesystem path (such are /tmp/)
  • $#   event-related file name
  • $%   event flags (textually)
  • $&   event flags (numerically)

With the events and variables out the way we can construct the command I will show you an example then explain it.

So the example is this(extra points if you can figure out what this is running)

/data/test.txt IN_MODIFY echo "$$ $@ $# $% $&"

This example is equivalent to running when /data/test.txt modified.

echo "$ /data test.txt IN_MODIFY 2"


Note: If you find that incron is not running your script/task, you may need to provide the full path of the program

Below is an example of using a python script when a file is created.

/data IN_CLOSE_WRITE /usr/bin/python / $#

As you can see I am providing the full path to the python interpreter as incron cannot find it.