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
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
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
Force executing the command ∞
Do this to force an execution of the command even there is no updates to the monitored files
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
$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.