Is there some way of telling when a change in hardware has been found in linux besides repeatedly polling for all the hardware and checking for changes?

For instance, I wrote a script to mount my phone's storage and backup all of the new pictures that I have taken. I would like the script to automatically be run when I plug my phone in to the usb port.

Is there some way that I can have my OS (debian jessie) tell me when a hardware change occurs?


Here's a way to run a bash script upon detection of a USB drive.

Connect your device and run lsusb to retrieve the device's info. You should see something similar to this:

$ lsusb
Bus 002 Device 039: ID 0bc2:2100 Seagate RSS LLC

In this case, the vendor ID of the device is 0bc2 and the product ID is 2100.
Now you can create a UDEV rule.

$sudo vi /etc/udev/rules.d/85-my_usb_device_rule.rules

And add this:

ACTION=="add", SUBSYSTEM=="usb", SYSFS{idVendor}=="0bc2", SYSFS{idProduct}=="2100", RUN+="/home/myhome/my_script"

/home/myhome/my_script is the path to your script which it would do whatever you want.

To make sure the detection script will execute right away reload the UDEV rules:

$sudo udevadm control --reload-rules
  • Two questions, is there any way to tell apart two devices that have the same vendor and product id? E.g. two usb sticks from the same company. Also why is the .rules file prefaced with an 85-? – nullUser Sep 18 '14 at 18:42
  • @nullUser That is a good question. I have not tried the situation with two of the same devices, therefore I don't have an answer for you. As for the rule number, no, it doesn't have to be 85. – slybloty Sep 18 '14 at 22:52

Each "file system" has an available UUID. Some also have a "label." (Read 'man mount') Once you connect your USB drive, your script runs. That script could then inquire about the UUID or label of the newly connected file system. Armed with that identifier, match it with the real-work script to run for that drive. I'd suggest a table {IDENT} {COMMAND} {COMMENT} so that you only need to edit to add new drives to the processing.

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.