In this lesson, you will learn how to make systemd services "wake up" automatically the moment a specific file or directory on your system is created, modified, or deleted.
Beyond Manual Starts
So far, you’ve managed services by starting them manually or triggering them via sockets. However, many administrative tasks—like processing a log file, syncing a configuration, or backing up a folder—only need to happen when a file changes. Instead of writing a custom script that runs in a loop checking for updates (which wastes CPU), you can offload this monitoring to systemd using Path Units.
How Path Triggering Works
Path-based triggering works by pairing two separate unit files:
- The Service Unit (
.service): Defines the task you want to run. - The Path Unit (
.path): Defines the "trigger" conditions.
When the systemd path monitor detects an event (like a file being written to), it automatically queues the associated service unit to start.
A Concrete Example
Imagine you want to run a script every time a file is placed in /opt/data/input/. First, create the service, then create the path unit:
/etc/systemd/system/processor.path
[Unit]
Description=Monitor input directory
[Path]
PathChanged=/opt/data/input/
Unit=processor.service
[Install]
WantedBy=multi-user.target
In this setup, PathChanged tells systemd to watch that specific directory. When a file is modified, systemd automatically triggers processor.service. You can also use PathExists (if you want the service to run only when a file appears) or PathModified (for specific content changes).
Why use this?
This mechanism is highly efficient because it leverages the Linux kernel's inotify subsystem. Instead of your service constantly "polling" the disk for changes, the kernel sends a notification to systemd only when the event actually occurs. This keeps your system lean and ensures your services only consume resources when they are truly needed to do work.
Key Takeaway: Path units decouple event detection from execution, using kernel-level file monitoring to trigger services only when specific filesystem changes occur.