Table of Contents

BASH - Directories - Monitor a directory for changes - Using incron

incron is like cron but instead of time-based events, the events are based on file notifications.


Install incron

sudo apt install incron

Change Permissions

Add users to the /etc/incron.allow file who are allowed to use incron.

/etc/incron.allow
peter

NOTE: One user per line.

/etc/incron.deny can also be used to specifically prevent usage of incron by a user.


Monitor

Edit the incron table:

incrontab -e

and populate with:

/etc/apache2/apache2.conf IN_MODIFY /usr/sbin/service apache2 stop

/home/peter/some_dir_to_watch IN_MODIFY echo "$$ $@ $# $% $&"

NOTE: This monitors the directory for changes and will perform the echo passing along some parameters.

The format is very picky; use spaces, not tabs!

  • The format is path mask command.

Parameters can include:

  • $$: Prints a dollar sign.
  • $@: The watched filesystem path.
  • $#: The event-related file name.
  • $%: The event flags/time (textually).
  • $&: The event flags.time (numerically).

Events to monitor include:

  • IN_ACCESS: If a file is accessed or read.
  • IN_ATTRIB: If metadata of a file change (e.g. timestamps, permissions).
  • IN_CLOSE_WRITE: If a file opened for writing is closed.
  • IN_CLOSE_NOWRITE: If a file or directory not opened for writing is closed.
  • IN_CREATE: If a file or directory is created in a watched directory.
  • IN_DELETE: If a file or directory is deleted from a watched directory.
  • IN_DELETE_SELF: If a watched file or directory is deleted (or moved to a different filesystem).
  • IN_MODIFY: If a file was modified.
  • IN_MOVE_SELF: If a watched file or directory is moved within the filesystem.
  • IN_MOVED_FROM: If a file or directory is moved out of the watched directory.
  • IN_MOVED_TO: A file or directory is moved to the watched directory.
  • IN_OPEN: A watched file or directory is opened.

IMPORTANT: incron is not capable of watching sub-directories.

Only files within the path will be monitored.

If sub-directories need to be monitored, they must be given their own entry.


List the incron table

incrontab -l