Using udev rules to run a script on USB insertion

I had the same problem. This worked for me:

Try to copy your script into /usr/local/bin and change the directory in your .rules file.

Also, I don't know what SYSFS is, but I would prefer to use the ATTR properties.

The following line is the content of my .rules file:

ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd[a-z]1", ATTRS{vendor}=="SanDisk ", RUN+="/usr/local/bin/backup.sh"

notify-send requires access to your DBus session bus, which it cannot have for two reasons:

  • No information about the session. When started by udev, your script knows nothing about where you are logged in or if you're logged in at all. Multi-seat with X11 is still tricky, but user switching works for both X11 and console sessions. Many people also use SSH, VNC and NX over the network.

    (DISPLAY=:0 would work half of the time, but that's still guessing at best.)

  • Denied by DBus policy. Even if your script somehow finds your X11 session, it will not be able to send notifications due to the script being run as root instead of your user account.