I have several USB mass storage flash drives connected to a Ubuntu Linux computer (Ubuntu 10.04.1, kernel 2.6.32-25-386), and I need to tell them apart programatically (from
I'm not sure in which kernel version this was implemented, but the /sys/block/*
entries are symlinks to the devices.
In other words, /sys/block/sdb
symlinks to a different directory, and its name contains the USB device ID.
$ file /sys/block/sdb
/sys/block/sdb: symbolic link to `../devices/pci0000:00/0000:00:02.1/usb1/1-1/1-1.1/1-1.1:1.0/host31/target31:0:0/31:0:0:0/block/sdb'
USB version and port here---^^^^^
The 1-1.1
is the interesting part, denoting usb1-port 1.device 1
. When plugged into a hub, another level is added: 1-2.3.1
, denoting usb1-port 2.port 3.device 1
.
Pseudocode:
get partition name # e.g. /dev/sdb1
get disk name # that would be /dev/sdb
get your basename # sdb
see where /sys/block/$your_basename points to # e.g. ../devices/blah/blah/1-2.1/blah
get the longest substring matching "\d-\d+(.\d+)*" # e.g. 1-2.1
that is the device id you want
/sys/bus/usb/devices/$device_id/ has all kinds of information about it
the ID corresponds to hardware USB ports
Working example script in bash.