Course contentsShow
← Linux
Lesson 1287 of 1,81911. Automation and System SchedulingFree lesson

Reacting to Mount and Unmount Events

Automate backup or cleanup routines triggered by filesystem activity.

In this lesson, you will learn how to trigger automated cleanup or backup routines the moment a filesystem is mounted or unmounted using udev rules.

While inotify is excellent for monitoring specific file modifications, it is not designed to track the lifecycle of entire filesystems. When you need to perform an action—such as triggering a backup script when a portable drive is plugged in or clearing a temporary cache directory when a partition is unmounted—udev (the Linux device manager) is the standard tool for the job.

The udev Approach

udev listens to the kernel’s device events. Every time a block device (like a USB stick or a network mount) is attached or removed, the kernel broadcasts an event. We can intercept these events to launch background service units.

To react to these events, you create a rule file in /etc/udev/rules.d/. For example, to trigger a backup script whenever a specific partition is detected:

ACTION=="add", SUBSYSTEM=="block", ENV{ID_FS_LABEL}=="MY_BACKUP_DRIVE", TAG+="systemd", ENV{SYSTEMD_WANTS}="backup-routine.service"

Decoupling Logic

Notice that the rule doesn't run the backup command directly. Following our previous lessons on Service Unit Encapsulation (13), we use the rule to pull in a systemd service unit. This allows you to manage the backup process as a formal system task rather than an arbitrary script running in the background.

By setting TAG+="systemd" and using ENV{SYSTEMD_WANTS}, udev tells systemd to start your service unit. Because this service is now managed by systemd, you gain all the benefits we’ve discussed previously, including Resource Constraints (18) and Monitoring Background Job Health (4).

When the device is unplugged, you can use an ACTION=="remove" rule to trigger a cleanup service, ensuring that temporary mount points are wiped or log files are rotated, preventing stale data from lingering on your system. This event-driven approach is far more efficient than polling the filesystem with a timer, as it executes immediately upon hardware state changes.

Key Takeaway: Use udev rules to bridge filesystem mount/unmount events into the systemd ecosystem, allowing you to trigger automated maintenance tasks exactly when hardware states change.