React to plugging devices with udev rules
The udev system allows to specify rules to react to the plugging of some devices.
This page is adapted from the ArchWiki. Also see writing udev rules
Execute a script when plugging a device
First, create the script to execute. Beware that it should not spawn long-running processes as processing of further events is blocked until the script has finished executing and background tasks spawned by the rule will be killed when the rule processing has finished.
If there is a need for long-running processes use at or similar systems to spawn them detached (e.g. a systemd unit)
- Find the current device name in the
/devhierarchy. A way to do so is to compare the hierarchy before and after plugging the device in. udevadm info --attribute-walk --name={device name (e.g. /dev/video0)}to list all udev attributes that can be used in a rule- Choose any number of attributes from the device and any number of attributes from one of the parent devices
- Create a rule file under
/etc/udev/rules.dits name must end with.rules- Rules are ordered by the name of the rule file.
- All rules matching a device (in any file) will be executed, only the order is changed by the file names.
- Add a rule for the device in the form:
ATTR1==VALUE1, ATTR2==VALUE2, RUN+="{path to script}"using the chosen attributesACTION=="add"orACTION=="remove"can also be added to only execute the rule on plugging or unplugging- The rule can only be on one line, there is no way to continue the rule on multiple lines (each line not starting with a
#will be considered a new separate rule)
- All file modifications should be automatically picked up by udev.
udevadm control --reloadwill force the reload rules- Rule will normally not be executed on devices that are already plugged in. Either unplug the device and plug it in again, or execute
udevadm trigger
- To list the rules that will be applied to a device (and also check their syntax), run
udevadm test {device name (e.g. /dev/video0)}