Categories
Linux

Run script on USB device insertion

Udev is a device manager for the Linux kernel and can be of great help to trigger activities when devices are added or removed. Once such scenario could be to run a script when the user connects a USB memory stick.

Udev is a device manager for the Linux kernel and can be of great help to trigger activities when devices are added or removed. Once such scenario could be to run a script when the user connects a USB memory stick.

The first thing necessary to write udev rules is to have information about the device to create filters. However, I had a hard time finding information about what filters were available when I wanted to write a set of matching rules that would not cause a number of false triggers. To do this use the following command (replacing the device name to whatever device you want information about):

udevadm info -a -n /dev/sdb1

The following is an example of a command that can be used to run a script whenever a USB device is inserted.

ACTION=="add",KERNEL=="sd?1",SUBSYSTEM=="block",RUN+="/usr/bin/usb_insert %k"

The parameter %k to the script will be converted by udev to the device that caused the event. Note that the line is wrapped here but must be stated as a single line in the system.

css.php