systemd path units: triggering a script the moment a file changes

The inotify wrapper that's been sitting in your init system the whole time

Contents

I used to run a cron job every minute to check whether a directory had a new file in it, which meant new files sat waiting up to sixty seconds before anything happened, and meant a process woke up 1,440 times a day to do nothing almost all of them. Then I actually read the systemd.path manual page properly instead of skimming it for the syntax, and realised the thing I wanted already existed as a first-class unit type, reacting the moment the filesystem changed rather than polling for it.

Why this isn’t just cron with extra steps

A path unit is a thin, declarative wrapper around the kernel’s inotify API, which lets a process register interest in a specific file or directory and get woken up by the kernel itself the instant something happens to it — a write, a create, a delete, an attribute change. Polling, whether it’s a cron job or a shell loop with a sleep in it, has a structural trade-off baked in: check often and you waste cycles almost every time; check rarely and you introduce latency between the event and your reaction to it. inotify has neither problem, because nothing runs until the kernel says something changed, and it says so immediately.

systemd wraps this in the same unit-file syntax as everything else it manages, which means a path unit gets the process supervision, logging, dependency ordering, and systemctl status visibility that a bare inotify script cobbled together with inotifywait in a while true loop simply doesn’t get for free. Plenty of tools watch files; the actual pitch is watching files using the same operational tooling as the rest of your system already runs on.

The three watch types that matter

A path unit’s [Path] section supports several directives, but three cover almost every real use case.

A disassembled electric doorbell laid out on graph paper: push button, wiring, terminal block and chime mechanism.
A doorbell is an event trigger in its simplest form: nothing runs until a press closes the circuit, as a path unit waits for a file event. Photo: Electric doorbell by Dmitry G, CC BY-SA 3.0, via Wikimedia Commons.

PathExists= fires (and keeps firing on every check) as long as the given path exists at all — useful for reacting to a lock file or a flag file appearing, less useful for anything that changes repeatedly, since it doesn’t distinguish “just appeared” from “still there.”

PathChanged= fires when a file’s content changes, specifically watching for the file being closed after being opened for writing — this is the one you want for “a script dropped a new file, now do something with it,” and it’s the directive most homelab automation actually reaches for.

PathModified= is similar to PathChanged= but also fires on attribute changes, not just content writes — a permissions change or a timestamp touch will trigger it even if the file’s bytes never moved, which is occasionally exactly what you want and occasionally a source of unwanted extra triggers if something else on the box touches the file’s metadata for unrelated reasons.

DirectoryNotEmpty= watches a directory rather than a single file and fires whenever it stops being empty, which is the one to reach for when you don’t know the filename in advance — a drop folder where anything landing in it should get picked up, rather than one specific file you’re watching for changes.

A worked example: processing dropped files

Say you want anything landing in a drop folder — a scanned document, an export from another system, a backup archive copied in by another job — picked up and processed the moment it arrives, rather than on the next poll interval. Two unit files, paired by name the same way a .timer pairs with a .service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# /etc/systemd/system/process-drops.path
[Unit]
Description=Watch drop folder for new files

[Path]
DirectoryNotEmpty=/var/lib/dropbox/incoming
Unit=process-drops.service

[Install]
WantedBy=multi-user.target
1
2
3
4
5
6
7
# /etc/systemd/system/process-drops.service
[Unit]
Description=Process files in the drop folder

[Service]
Type=oneshot
ExecStart=/usr/local/bin/process-drops.sh

Note the service is deliberately Type=oneshot, not a long-running daemon — the path unit itself is the thing sitting resident and watching; the service it triggers should do its job and exit. Enable and start the path unit, not the service directly:

1
$ sudo systemctl enable --now process-drops.path

systemctl status process-drops.path will show you what it’s watching and whether it’s active; journalctl -u process-drops.service shows you what happened each time it fired, which matters because a path unit that fires correctly but whose triggered service fails silently is a very easy thing to miss without checking both units, not just the path unit’s own status.

The gotcha almost everyone hits first

PathChanged= fires once per write-then-close cycle, and a process copying a large file typically does several open-write-close cycles as it writes in chunks, or a tool like rsync writes to a temporary filename and renames it into place at the end. If your service triggers on the intermediate writes rather than the final rename, you’ll process a half-written file. The fix isn’t in the path unit at all — it’s making sure whatever writes into the watched location does an atomic rename into place rather than writing in-place, which most well-behaved tools already do, and checking that your triggered script is defensive about a file that might still be growing regardless. A short ExecStartPre= guard that checks the file size is stable across a brief sleep, or that waits on a companion .done marker file written after the real payload, closes this gap cleanly without adding complexity to the path unit itself.

Rate limiting a noisy source

A directory that gets written to rapidly — a busy upload folder, a log rotation writing several files at once — can fire a path unit’s trigger many times in quick succession, and each firing starts a fresh instance of the triggered service if the previous one hasn’t finished. systemd’s own StartLimitIntervalSec= and StartLimitBurst= in the triggered service’s [Unit] section cap how many times it’ll restart within a window, which protects against a genuinely runaway trigger loop, but the more useful day-to-day fix for a merely bursty source is setting Type=oneshot with RemainAfterExit=no combined with a lock so overlapping triggers queue rather than run concurrently and step on each other:

1
2
3
[Service]
Type=oneshot
ExecStart=/usr/bin/flock -n /run/process-drops.lock /usr/local/bin/process-drops.sh

flock -n fails fast rather than blocking if another instance already holds the lock, which for a oneshot triggered repeatedly by a bursty directory is usually the right choice — better to skip a redundant run and let the next trigger catch whatever was missed than to pile up queued invocations.

Path units versus a bespoke inotify script

It’s worth being honest about where a hand-rolled watcher still wins. A path unit’s granularity stops at “something happened in this location” — it doesn’t tell your triggered service which file changed inside a watched directory, so the service itself has to work that out, usually by listing the directory and figuring out what’s new since last time. A script built directly on inotifywait --format gets the changed filename handed to it directly in the event, which is a real ergonomic win if your logic genuinely needs to act on individual files differently rather than just “re-scan the directory.” For almost everything else — restart trigger, rebuild trigger, notify trigger — the path unit’s coarser granularity is a feature, not a limitation, because it keeps the unit declarative and the actual file-handling logic in the script where it’s easier to test and reason about independently of the trigger mechanism.

A second example: rebuilding on config change

The drop-folder pattern above is the obvious use case, but the one I actually reach for most often is reacting to a single config file changing rather than a directory filling up — reloading a reverse proxy the moment its config is edited, without a human remembering to run the reload command afterward.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# /etc/systemd/system/reload-proxy.path
[Unit]
Description=Watch reverse proxy config for edits

[Path]
PathChanged=/etc/myproxy/myproxy.conf
Unit=reload-proxy.service

[Install]
WantedBy=multi-user.target
1
2
3
4
5
6
7
# /etc/systemd/system/reload-proxy.service
[Unit]
Description=Reload reverse proxy after config edit

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl reload myproxy.service

This is a small thing, but it changes a habit: instead of “edit config, remember to reload, occasionally forget and wonder why nothing changed,” editing the file is the reload, and the two are impossible to get out of sync because there’s no separate step to skip. The same pattern generalises past reverse proxies to anything with a well-defined reload mechanism — a DNS resolver picking up a new zone file, a monitoring agent picking up a new set of scrape targets, a firewall reloading a ruleset after an edit. Wherever a piece of software already exposes a clean reload path, wiring a path unit in front of its config file removes the manual step entirely rather than automating the reminder to do it.

Where this sits in the boot dependency graph

Because a path unit is a normal systemd unit like any other, it participates in the same dependency ordering as services do, which matters more than it first appears. A path unit that watches a location on a filesystem that isn’t mounted yet at boot will fail to establish its watch, not queue politely until the mount appears — so a path unit watching something under a separately mounted data volume needs an explicit After= (and often Requires=) on the relevant .mount unit, exactly the same dependency you’d add to a service that reads from that same location. This is easy to miss because path units feel lightweight and background, almost invisible compared to a service, but they’re subject to the same ordering rules as everything else systemd starts, and a path unit that silently fails to activate at boot because its target directory wasn’t mounted yet looks, from the outside, exactly like a path unit that’s working fine and just hasn’t fired — systemctl status on it will show active/waiting either way unless you look closely at the activation timestamp relative to when the underlying mount actually came up.

Troubleshooting

The path unit is active but never fires. Check that the watched path actually exists at the directory level systemd needs — DirectoryNotEmpty= needs the directory itself to already exist when the unit starts, it won’t create a watch on a path that doesn’t exist yet and silently wait for the parent to appear. Create the directory first, then start the path unit.

It fires once and then stops firing on subsequent changes. This is almost always PathExists= used where PathChanged= was needed — PathExists= considers its job done once the condition is true and the file remains, and won’t re-fire on further modifications to that same file the way PathChanged= does.

The triggered service runs but the path unit’s own status looks stale. systemctl status on a path unit shows its activation state, not the triggered service’s — check the service’s own status and journal separately, they’re two units connected by convention (matching filename stem) or an explicit Unit= directive, not one combined thing.

Watching a network filesystem mount doesn’t work reliably. inotify’s kernel-level notification depends on the underlying filesystem actually emitting the right events, and NFS in particular is known to miss or delay inotify events for changes made by other clients mounting the same share — changes from the local machine work fine, changes from elsewhere on the network may not be seen promptly, if at all. For a shared network location, a periodic timer-triggered poll is more honestly reliable than a path unit that appears to work in testing (where you’re the only writer) and quietly misses events in production (where you’re not).

Multiple path units watching overlapping locations fire more than expected. If a parent directory and a file inside it both have watches attached — one DirectoryNotEmpty= on the folder and one PathChanged= on a specific file within it — a single write can legitimately trigger both, since they’re watching genuinely different things that both happened to change together. This isn’t a bug so much as a reminder to be deliberate about which layer you’re actually watching, and to make triggered services idempotent enough that being invoked twice for the same underlying event doesn’t cause harm.

Is it worth reaching for

Any time the reaction needs to be immediate rather than “within the next polling interval,” yes, and it costs nothing extra to set up beyond the two short unit files above — no daemon to babysit, no extra package to install since inotify support is already in the kernel and systemd already links against it. Where it doesn’t help is watching something outside the local filesystem’s event stream, like a remote API or a database row, where there’s nothing for inotify to hook into and a timer-driven poll is the honest answer rather than something to work around.

For the timer-based alternative when polling really is the right tool, see the cron replacement you should probably be using, and for reading what a triggered service actually did after the fact, see reading status and journal like a pro.

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.