How to run custom scripts upon USB device plug-in?

Put a line like this in a file in /etc/udev/rules.d:

KERNEL=="sd*", ATTRS{vendor}=="Yoyodyne", ATTRS{model}=="XYZ42", ATTRS{serial}=="123465789", RUN+="/pathto/script"

Add a clause like NAME="subdir/mydisk%n" if you want to use a custom entry path under /dev.

Run udevadm info -a -n sdb to see what attributes you can match against (attribute=="value"; replace sdb by the device name automatically assigned to the disk, corresponding to the new entry created in /dev when you plug it in). Note that you can use ATTRS clauses from any one stanza: you can pick any stanza, but the ATTRS clauses must all come from the same stanza, you can't mix and match. You can mix ATTRS clauses with other types of clauses listed in a different stanza.


I looked into /lib/udev/rules.d for examples of disk related rules. On an Ubuntu system one rule file provides the environment variable ID_FS_UUID_ENC which you can use in own rule files.

Thus I put a custom rule file under /etc/udev/rules.d/foodevice.rules. Since it is not prefixed with a number, it is ran at last by udev. Btw, the udev daemon watched /etc/udev/rules.d for changes such that you don't need to restart it on file changes.

The content of /etc/udev/rules.d/foodevice.rules is:

ACTION=="add", KERNEL=="sd*[!0-9]", ENV{ID_FS_UUID_ENC}=="FFFF-AAAF",
  RUN+="/usr/bin/sudo -u juser /home/juser/path/script.sh"

(this is one rule - you have to remove the newline after the ENV clause because udev does not have a line continuation mechanism)

A program started by udev blocks the daemon - thus it shouldn't run for a long time. I solved it via at - i.e. via detaching from the process doing the real work:

$ cat /home/juser/path/script.sh
#!/bin/sh
echo ~/path/mountcopystuff.sh | at now

Tags:

Uuid

Usb

Udev