Rerun a test when files change with Watchexec
Watch a small project with Watchexec, trigger passing and failing runs, and ignore generated files.
Updated
in short
Run a test command under Watchexec. Changes under the watched directory trigger another run; an ignore pattern keeps generated output from causing loops.
Use the small fixture below to check the workflow before applying it to your own project.
Tools used
Before you start
- A Bash or Zsh terminal on Linux or macOS
- The listed tools installed and available on PATH
Steps
Step 1: Create a tiny test
The test succeeds only while answer.txt contains 42. Print the directory so you can open it in a second terminal.
shtrmn_guide_dir="$(mktemp -d)" cd "$trmn_guide_dir" printf '42\n' > answer.txt cat > test.sh <<'EOF' #!/usr/bin/env sh if [ "$(cat answer.txt)" = 42 ]; then printf 'PASS\n' else printf 'FAIL\n' exit 1 fi EOF pwd sh test.shStep 2: Start the watcher
Leave this running. The command runs once at startup, then after relevant file changes.
shwatchexec --watch . --ignore 'generated/**' -- sh test.shStep 3: Trigger a failure and recovery
In a second terminal, cd to the directory printed earlier. Run the first line, observe FAIL, then run the second and observe PASS.
shprintf '0\n' > answer.txt printf '42\n' > answer.txtStep 4: Stop watching
Press Ctrl-C in the watcher terminal. Keep generated output in the ignored directory to avoid a self-triggering loop.
Further reading
[Watchexec repository and CLI docs](https://github.com/watchexec/watchexec)
FAQ
- Does the watcher stop after a failing test?
- A failing child command does not normally end the watcher. It can run the test again on the next change.
- Will rapid saves produce one run each?
- Not necessarily. Filesystem events can be grouped, so wait for each result while trying the example.