Running a Command Upon Files or Directories Changes on Linux

Doing actions upon changes of files and directories is very useful. Examples like compiling a project after the source code files are changed, sending emails after important configuration files are modified, building the PDF after a TeX file is modified. On Linux, the inotify-tools provide good support for trigger actions after changes. In this post, I will introduce a small tool do-after-change.sh which continuously runs a command upon certain files and directories change.

The script makes use of inotifywait which is from the inotify-tools package. On Fedora/RHEL/CentOS/SL, you can install the package by yum install inotify-tools. You may need to install similar packages on other Linux distros such as Debian/Ubuntu/Linux Mint.

How to use do-after-change.sh

The usage

The command format

do-after-change.sh cmd watched_files

where cmd is the command to execute and watched_files are the files to be watched.

One example, to make a project after certain .c, .h or Makefile files change:

do-after-change.sh "make" *.c *.h Makefile

or pass options to the command like make install:

do-after-change.sh "make install" *.c *.h Makefile

The script will continuously monitor these files and invoke the command if they are updated.

Note that if the files are changed during the execution of the cmd, these updates will not trigger the cmd again.

Force executing the command

Do this to force an execution of the command even there is no updates to the monitored files

touch /tmp/doafterchanges

How does it work

The most important part in the script is:

while true; do
    inotifywait -q -r $files $cmdfile
    exec_cmd
done

inotifywait waits for the changes from $files which is from the options to do-after-change.sh and $cmdfile which is /tmp/doafterchanges for the forcing cmd execution function.

exec_cmd is to execute the cmd from the option with some pre and post messages indicating what’s going on.

This small tool provides the basic loop of “file change” -> “run command”. Many applications can be built upon it. Let me know by commenting if you find it useful or build some interesting commands on top of it. Enjoy.

Eric Zhiqiang Ma

Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

2 comments:

  1. I’m going to use this to upload audio files to an Icecast Server after they’re cleared for broadcast quality and have been dumped into a LAN NAS directory.

    Thank you very much for your clear explanation of inotifywait.

    Regards
    Nick

Leave a Reply

Your email address will not be published. Required fields are marked *