Udev rule to match any usb storage device

udev

How can I implement udev rules for any USB mass-storage device plugged in, not just for specific one? What should be changed in idVendor, and idProduct?

 ACTION=="add", SUBSYSTEM=="usb", SYSFS{idVendor}=="0204", SYSFS{idProduct}=="6025",
     RUN+="/home/workspace/bash_script.sh"

Best Answer

A storage device is in the block subsystem, so you'll want SUBSYSTEM=="block" in your rule, like this:

ACTION=="add", KERNEL=="sd?", SUBSYSTEM=="block", ENV{ID_BUS}=="usb", \
    RUN+="/path/to/script"

If you're using systemd, you could run a systemd unit each time a USB storage device is added. Create the unit file, e.g. /etc/systemd/system/my-usb-rule.service:

[Service]
Type=oneshot
ExecStart=/path/to/script

and the rule, e.g. /etc/udev/rules.d/85-my-usb-rule.rules:

ACTION=="add", KERNEL=="sd?", SUBSYSTEM=="block", ENV{ID_BUS}=="usb", \
    ENV{SYSTEMD_WANTS}="my-usb-rule.service"

Now udev will trigger my-usb-rule.service (which in turn will execute your script) on any usb storage device add event.


Don't forget to reload the configuration after you edit the rules/units:

udevadm control --reload
systemctl daemon-reload
Related Question