User Tools

Site Tools


linux:watch_file_changes

Watch files for changes (howto)

or

How to execute a command whenever specific files change.

Maybe you've heard of fswatch, but I don't really like it because of its complexity.

There's a perfect and easy to use alternative: entr. It's a command line tool which accepts filenames through a pipe, keeps an eye on them and then does anything you want (it may even not be related to the watched files). This tool can be found in almost all GNU/Linux distros.

First example

Watch for all .ts (TypeScript) file changes in directory src/ and translate them to .js (JavaScript) and save them into directory dist/.

The necessary tool for translation (transpilation) may be Deno, SWC or Bun, I recommend the last one. Don't even think of tsc, it's ultra slow.

The basic usage of entr is this:

ls *.extension | entr -ps 'command_to_be_executed'

Or even simpler if you want to watch only one file:

echo file_name | entr -p command_to_be_executed /_

After you have bun downloaded (the standalone version, not the NPM package) you can simply put this command into a shell script:

ls src/*.ts | entr -ps 'bun build src/main.ts --target browser --outdir=dist'

OK, in the example above we are watching for all file changes but in the end only main.ts is passed to the last command. Why is this? Because it's the main script file and bun automatically checks all dependent files and bundles everything together.

Second example

Another example which performs an action on every watched file individually ($0 stands for the filename where a change has been detected):

ls *.txt | entr -ps 'command_to_be_executed $0'

Entr man page here

linux/watch_file_changes.txt · Last modified: 2024-02-15 11:27 by admin