Execute command on file modification

At some point, every programmer will embark in the quest of AUTOMATING ALL THE THINGS and stumble on the case of executing a particular command when a file is modified. This is the kind of simple trick that has so many applications:

  • Calling latexmk whenever a tex file is modified
  • Running specific unit tests when you edit code
  • Downloading subtitles when a movie download finishes

All of this can be done with a single command line. We will detail the command in the context of a Unix system using fswatch. For Linux systems, you may want to check out inotify-tools and inotifywait.

When calling

$ fswatch path
fswatch monitors changes to path and outputs path to the standard output whenever a change occurs.

Therefore, we just need to pipe fswatch with xargs to execute a certain command on that path. The man pages and this documentation details how to construct this pipe. For our latex file example, the command would be:

fswatch -0 file.tex | xargs -0 -n 1 latexmk -pdf

fswatch is an amazing tool: simple to use and at the same time provides more complex monitors for advance usage. Of course, you could set up your ide to call latexmk whenever you save your tex file but you cover more use cases when doing it generically from the command line ;)