Do something when a file is changed
When I write a LaTeX document, I find myself to press F6 in my editor to compile often. Or when I use SASS, I often type make
to convert my .scss
into .css
.
Now I would like to let the machine do the dirty work and run make
or something else every time a given file change.
So far I kept a terminal window open and pressed arrow-up and return. Or I used watch make
, but that seems like an odd solution.
Is there a nice way on Linux to do something when a given file changes?
Solution 1:
You're looking for inotifywait
, part of inotify-tools. There are some examples of how to use it on the project's site but a simple approach is,
while true; do inotifywait code.cpp -e modify; make; done
the key part of which is,
inotifywait code.cpp -e modify
That command will wait until code.cpp
is modified then exit. Put in the infinite loop and followed with make
causes it to constantly rebuild after every modification.
Besides waiting on modify, you can wait on creation, deletion, access, opening, closing, and more. I highly recommend looking at the project examples and inotifywait man page for some other ideas on how it can be used.
Solution 2:
Have a look at incron, a cron-like package that responds to filesystem events, instead of time events. The package consists of a daemon (incrond
) and a table manipulator (incrontab
), analogous to the well-known crond
/crontab
pair of cron.
With incron, you could easily arrange to run make
whenever particular files and/or directories are modified.