In this lesson, you will learn how to trigger automated scripts instantly when specific hardware devices are plugged into or removed from your Linux system.
While cron and systemd timers are excellent for time-based tasks, they cannot react to spontaneous events like inserting a USB drive or connecting a peripheral. This is where udev (userspace device manager) becomes essential. udev listens to the kernel’s device events and allows you to execute custom actions the moment a device is identified.
Crafting a Rule
You define these actions by creating custom rule files inside /etc/udev/rules.d/. These files follow a specific syntax that filters events based on device attributes. For example, to trigger a script every time a specific USB drive is inserted, you would create a file named /etc/udev/rules.d/99-usb-backup.rules containing:
ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="1234", RUN+="/usr/local/bin/backup_script.sh"
In this rule:
ACTION=="add"ensures the command runs when the device appears.SUBSYSTEM=="usb"filters for USB devices.ATTR{idVendor}pinpoints your specific hardware.RUN+=specifies the script to execute.
Important Considerations
When writing these scripts, keep two constraints in mind. First, udev executes scripts immediately; if your script is long-running or performs heavy I/O, it can block the device manager from processing other events. It is best practice to have the udev rule trigger a systemd service unit instead of running a complex script directly. This allows the event to be "handed off" to the background, keeping the kernel event loop responsive.
Second, avoid using relative paths. Because udev environments are restricted, always use absolute paths for your binaries and scripts (e.g., /usr/bin/logger instead of logger) to ensure the command is found regardless of the path environment.
By combining udev rules with systemd services, you create a robust bridge between physical hardware changes and system-level automation, allowing your server to "respond" to its environment rather than just waiting for the clock to tick.
Key Takeaway: Udev allows you to move beyond time-based scheduling by triggering automated tasks directly from hardware insertion or removal events.