Rerun a test when files change with Watchexec

Watch a small project with Watchexec, trigger passing and failing runs, and ignore generated files.

how-to4 steps

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

  1. 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.

    sh
    trmn_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.sh
  2. Step 2: Start the watcher

    Leave this running. The command runs once at startup, then after relevant file changes.

    sh
    watchexec --watch . --ignore 'generated/**' -- sh test.sh
  3. Step 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.

    sh
    printf '0\n' > answer.txt
    printf '42\n' > answer.txt
  4. Step 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.

related