Shell – How to trigger an event in shell script when an USB device is removed

linuxshell-scriptusb

I need to do some actions when a specific USB device is removed/added. I need a fast response on the order of milli-seconds.

How can I do this in a shell script?

Best Answer

Assuming you are using a Linux distribution with udev support and you have root/administrator access to it then you can use udev rules to trigger on specific operations.

If the following example is added to a /etc/udev/rules.d/example.rules then it will run the specified script when a block device is added with the specified parameters.

ACTION=="add", SUBSYSTEM=="block", ATTRS{manufacturer}=="HitachiGST", ATTRS{serial}=="31001206110000000000", RUN+="/a/script/to/run.sh"

That particular rule executes when my USB harddrive is inserted and attaches to the block system. It is quite easy to tweak the rules to match a specific lowlevel USB event.

I found the Debian UDEV wiki page and Writing Udev Rules site to be very helpful in getting the right rules for my situation.