1

I'm writing a bash script that needs to detect when a usb storage device is inserted and assign it to a variable that would otherwise, typically look something like: usb=/dev/sdb.

I have a few abstract ideas that involve using watch, some kind of if / while looping construct, and possibly lsblk -o kname / lsblk -o pkname; but am yet to fully realize anything suitable.

How best could I implement this?

1

You can kick off a script using UDEV. "udev also handles all user space events raised while hardware devices are added into the system or removed from it" (From http://wiki.archlinux.org/index.php/Udev)

Inside a file called: /etc/udev/rules.d/10-usb.rules add the following:

KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/path/to/script.sh"

Note: You may need to slightly adjust the location of the file depending upon your distribution. Also Note: You may need to restart before the rule takes effect.

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.