Watching Files Change With inotifywait and entr

Two small tools that turn the kernel's own file-change events into a script you can act on

Contents

The first version of every “run this when that file changes” script I ever wrote was a while true loop checking a file’s modification time every second and sleeping in between. It works, technically, in the sense that it eventually notices a change — but it burns CPU checking nothing has happened most of the time, it can miss rapid successive changes between polls, and the latency is bounded by however long your sleep is. The kernel has had a proper answer to this since 2.6.13: inotify, a subsystem that lets a process register interest in a file or directory and receive an event the instant something happens to it — no polling, no sleeping, no missed changes. inotifywait and entr are two small userspace tools built directly on top of it, and between them they cover almost every “do X when Y changes” script I’ve ever needed.

What inotify actually gives you

inotify is a kernel-level API: a process opens an inotify file descriptor, adds watches on specific paths, and then blocks on that descriptor until the kernel delivers an event: a file was modified, created, deleted, moved, had its attributes changed, and several more specific event types. The process is asleep, consuming no CPU, until the kernel itself wakes it up because something the kernel is already tracking happened. That’s the structural difference from polling: polling asks “has anything changed?” repeatedly; inotify has the kernel tell you the moment it does, exactly once, with zero cycles spent while nothing is happening.

Stacked sheets of paper on a dark desk with a ripple of light spreading from one changed sheet.
Illustration of a watcher reacting to one changed file; a concept image. AI-generated illustration.

inotifywait: the raw event stream

inotifywait, from the inotify-tools package, is the most direct way to see this from a shell. Pointed at a path, it blocks until an event fires, then prints what happened and exits:

1
2
3
4
$ inotifywait /var/log/myapp/app.log
Setting up watches.
Watches established.
/var/log/myapp/app.log MODIFY

For anything more than a one-shot check, -m (monitor) keeps it running and printing every subsequent event instead of exiting after the first one, and -r makes a directory watch recursive:

1
2
3
4
5
6
7
$ inotifywait -m -r -e create,delete,modify /srv/uploads
Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.
/srv/uploads/ CREATE incoming.zip
/srv/uploads/ MODIFY incoming.zip
/srv/uploads/ MODIFY incoming.zip
/srv/uploads/ CLOSE_WRITE,CLOSE incoming.zip

That last line, CLOSE_WRITE, is usually the event you actually want rather than MODIFY — a large file being written triggers many MODIFY events as data streams in, but only one CLOSE_WRITE when the writer is actually done and closes the file descriptor. Triggering a script on MODIFY for a file still being written means processing a half-written file; triggering on CLOSE_WRITE means the write is complete.

Wiring it into a loop

inotifywait on its own just prints events; wrapping it in a shell loop turns those events into action. This watches a directory for finished uploads and processes each one as it lands:

1
2
3
4
5
6
#!/usr/bin/env bash
inotifywait -m -e close_write --format '%w%f' /srv/uploads |
while read -r file; do
    echo "processing: $file"
    ./process-upload.sh "$file"
done

--format '%w%f' prints just the watched-directory path plus filename, one per line, which is exactly what a while read loop wants. This is the shape of most inotifywait scripts I write: a monitor process feeding a loop that reacts to each event.

entr: simpler, when the trigger is “just rerun this command”

inotifywait gives you the raw event and format control; entr (event notify test runner) skips straight to the common case of “when any of these files change, rerun this command” without the loop-writing. It reads a list of filenames from stdin and re-executes a given command whenever any of them changes:

1
$ find . -name '*.py' | entr -r python3 app.py

That single line replaces a manual file-watching loop entirely: every time any .py file under the current directory changes, entr kills the running python3 app.py (that’s what -r, restart, does — necessary for a long-running server process rather than a one-shot command) and starts it again. For a one-shot command that should just rerun to completion rather than being restarted mid-flight, drop -r:

1
$ find . -name '*.scss' | entr sass style.scss style.css

entr reads the file list once at startup from stdin, which is worth knowing because it means newly created files matching your find pattern won’t be picked up until you restart the whole pipeline — add -d and entr will exit (so you can wrap it in a loop that re-runs find and re-starts entr) as soon as a new file appears in a watched directory, closing that gap.

Choosing between them

inotifywait is the better fit when you need to know what kind of event happened and which specific file, and you want to write custom logic per event type — the uploads-processing example above genuinely needs the filename and needs to distinguish CLOSE_WRITE from other events. entr is the better fit when the reaction is uniform regardless of which file changed or how — rerun the tests, restart the dev server, rebuild the docs — and you’d rather not write and maintain a loop at all. In practice I reach for entr far more often, because “rerun this build/test/restart command on any change” is the large majority of what I actually need, and entr’s one-liner beats hand-writing the loop every time.

A concrete pairing: live-reloading a local build

This is close to my actual ~/.local/bin/watch-build script — rebuild a static site on every content or template change and immediately show whether the build succeeded:

1
2
3
4
#!/usr/bin/env bash
find content layouts assets -type f | entr -c -s '
    hugo --minify && echo "[ok] build succeeded" || echo "[fail] build broke"
'

-c clears the terminal before each run so output doesn’t pile up illegibly across dozens of rebuilds, and -s runs the command through a shell so the &&/|| chaining works. Every save in an editor triggers a fresh build within milliseconds, with a clear pass/fail line at the end — the same category of workflow as compose watch for a Docker stack, generalised to any file on disk rather than only containers; see compose watch: live-reloading a development stack on file changes if your actual target is a containerised dev environment specifically.

The event types worth actually knowing

inotify exposes more event types than most scripts ever need, but a handful come up repeatedly enough to be worth memorising rather than looking up each time:

  • create — a new file or directory appeared inside a watched directory.
  • delete — a file or directory was removed.
  • modify — a file’s content changed (fires repeatedly during a write, not just once).
  • close_write — a file opened for writing was closed; the reliable “the write is finished” signal.
  • moved_to / moved_from — a file was renamed or moved into/out of the watched location; this is how atomic-save editors show up, and how mv-based deployment scripts trigger a watcher.
  • attrib — permissions, ownership, or timestamps changed without the content changing; rarely what you want to trigger a rebuild, but useful if you’re specifically watching for a permission fix.

Passing -e restricts inotifywait to only the events you list, cutting noise from types you don’t care about — the close_write,moved_to combination from the troubleshooting section below is the one I reach for most often, since between them they catch both a direct write-then-close and an atomic rename-into-place without also firing on every intermediate modify.

systemd path units: the alternative when you’d rather not run a script at all

For triggering a systemd service specifically, rather than an arbitrary shell command in a terminal you have to keep open, a .path unit is worth knowing about as an alternative — it uses the same inotify mechanism under the hood but is managed by systemd itself, starts on boot, and needs no wrapper script running in a terminal:

1
2
3
4
5
6
# /etc/systemd/system/process-uploads.path
[Path]
PathChanged=/srv/uploads

[Install]
WantedBy=multi-user.target
1
2
3
4
# /etc/systemd/system/process-uploads.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/process-uploads.sh

systemctl enable --now process-uploads.path and systemd itself watches the directory and starts the paired service on a change — no entr, no inotifywait, no shell loop that needs to survive a reboot on its own. It’s less flexible than a hand-written loop (no per-event filename passed through cleanly, no easy access to which specific event fired), which is exactly why I still reach for inotifywait or entr directly for anything interactive or development-focused, and save .path units for the cases where the reaction genuinely belongs inside a proper systemd-managed service rather than a terminal session.

inotify and network filesystems don’t mix

A gotcha that costs people real debugging time the first time they hit it: inotify is a Linux kernel feature that only works for changes the local kernel actually observes happening on a local filesystem. Point inotifywait or entr at a directory mounted over NFS, SMB/CIFS, or most other network filesystems, and changes made by a different client — another machine writing to that same share — generally won’t generate an inotify event on your machine at all, because the write happened on a different kernel that never told yours about it. Changes made locally, from the same machine holding the watch, often do still fire, which makes the failure mode particularly confusing: it looks like it’s working during testing (you’re editing locally) and then silently stops the moment the real writer is a different box on the network.

There’s no clean fix for this within inotify itself — it’s a fundamental limitation of how the API is wired to the local filesystem layer, not a bug in inotifywait or entr. The practical workarounds are: run the watcher on the same machine that’s actually writing the files, rather than watching a network mount from a second box; or, if that’s not possible, fall back to a short-interval polling loop specifically for that path (the one case where the polling approach this whole piece opened by dismissing is genuinely the right tool, because the alternative doesn’t exist over that transport). Some NFS server implementations support FAM/gamin-style change notification as a separate mechanism, but it’s far less universally available than plain inotify, and I’ve never found it worth chasing for a homelab-scale setup versus just moving the watcher to the box doing the writing.

Troubleshooting

“Failed to watch; upper limit on inotify watches reached” — the kernel caps the total number of inotify watches per user, and recursively watching a directory tree with a very large number of files (a big node_modules, a large media library) can hit it. Check and raise the limit:

1
2
3
$ cat /proc/sys/fs/inotify/max_user_watches
8192
$ sudo sysctl fs.inotify.max_user_watches=524288

Make it permanent in /etc/sysctl.d/ rather than just setting it live, or it resets on the next reboot.

Events firing multiple times for what feels like one save. Many editors don’t write a file in place — they write a new temp file and rename it over the original (atomic-save, to avoid corrupting the file on a crash mid-write). That shows up as a CREATE for the temp file, MODIFY, and a MOVED_TO/DELETE sequence rather than a single clean MODIFY on the path you’re watching, which can trigger entr or a naive inotifywait loop more than once per actual save. entr already debounces this reasonably well in practice; a raw inotifywait loop may need to explicitly watch for close_write,moved_to and ignore the rest.

Watching a symlink doesn’t see changes to the target. Both tools watch the path you give them; if that path is a symlink, you generally want to point the watch at the real target directory rather than the link, or add -h/consult the man page for the tool’s specific symlink-following behaviour.

When you’ve outgrown a shell loop

For anything that needs to survive a reboot, log its own activity properly, or coordinate with other scheduled work rather than run forever in a terminal, these ad-hoc watchers are the wrong final home — wrap the logic in a proper systemd service, and if the “job” framing fits better than “watcher,” a systemd timer alongside it covers the polling-adjacent cases inotify genuinely can’t (watching for absence of an event, or state that isn’t file-based at all). And if the reason you’re watching files in the first place is to catch a script failing silently, pair the watcher with a dead man’s switch for your cron jobs so a watcher that itself dies doesn’t fail silently too.

Is it worth reaching for

Yes, immediately, for anything better than a polling loop — which is almost everything. entr for “rerun this on any change” covers the large majority of cases in one line; inotifywait for anything that needs per-event logic. Both are small, both are already packaged for every major distro, and both replace a category of script (the while true; sleep 1 polling loop) that wastes cycles and adds latency for no benefit once you know the kernel already does this properly.

Smarc
Written by Smarc

Founder and editor of Aside House. A lifelong tinkerer who self-hosts far more than is sensible, hardens Linux boxes for fun, and prods the latest AI tools to see what they can really do. The how-to guides here are the notes Smarc wishes had existed the first time round.

Smarc is the editor of Aside House. The homelab, the hardware and the opinions are real; the guides are drafted with AI assistance. Infrastructure details are genericised on purpose.