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?

  • 1
    I don't know exactly how you could do this, but look into udev rules. that should help.
    – strugee
    Jan 6, 2014 at 16:22

2 Answers 2


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.


As an initial answer you could listen for changes in the file /proc/bus/input/devices and check for USB entries. With this you can avoid polling the device. Or you can perform a loop polling when the device is inserted.

Probably shell script won't be as fast as you want. Would be better to use another script language Python or C/C++.

http://libusb.sourceforge.net/doc/examples-code.html http://sourceforge.net/apps/trac/pyusb/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.