Ubuntu – How to run a Bash script every time is plugged an USB device


I'm using Ubuntu 18.04 and I need to run a Bash script every time is plugged a new USB device (interdependently from the device type).

PS: I found other answers able to works for a specified USB device, but I need to works for ANY possible USB device.

Best Answer

  • Start systemd .service from an udev rule

    udev monitor allows you to monitor kernel uevents and print the devpaths to the console, which can then be used by udevadm info -a --path='' to print all sysfs properties for all devices along the chain.

    udevadm monitor --environment --udev lets you monitor environment variable set by udev events after the rule processing.

    $ cat /etc/udev/rules.d/99-usb-autorun.rules
    # Start USB autorun systemd .service
    ENV{DEVTYPE}=="usb_device", \
    TAG+="systemd", ENV{SYSTEMD_WANTS}="usb_autorun.service"

    (dont forget to reload your rule udevadm control --reload && udevadm trigger).

    ...and /etc/systemd/system/usb_autorun.service:

    Description=USB Autorun.