get name and device file path of usb device attached

7,534

a lot of copy/paste brought me again here hoping that this would be helpful for others and also to improve my code

I used the almost perfect code from the answer in this question and added/removed some little stuff

#!/bin/bash

for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do
    (
        syspath="${sysdevpath%/dev}"
        devname="$(udevadm info -q name -p $syspath)"
        
        [[ "$devname" == "bus/"* ]] || [[ "$devname" == "input/"* ]] || [[ "$devname" == "video0"* ]] || exit
        
        eval "$(udevadm info -q property --export -p $syspath)"
        [[ -z "$ID_SERIAL" ]] && exit
        
        busnum="$(udevadm info -a -p  $(udevadm info -q path -n /dev/$devname) | awk -F "==" '/busnum/ {gsub("\"","");print $2}' | head -1)"
        devnum="$(udevadm info -a -p  $(udevadm info -q path -n /dev/$devname) | awk -F "==" '/devnum/ {gsub("\"","");print $2}' | head -1)"
        bus_dev=${busnum}:${devnum}
        lsusb="$(lsusb -s $bus_dev)"
        
        echo "$lsusb - /dev/$devname"
    )
done

output:

Bus 003 Device 005: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter - /dev/ttyUSB0

NOTE: i don't have any unix experience so if you would like to improve the code please do!

Share:
7,534

Related videos on Youtube

aster94
Author by

aster94

Updated on September 18, 2022

Comments

  • aster94
    aster94 over 1 year

    if i run the common lsusb i get something like:

    Bus 003 Device 003: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter

    but it doesn't show the device file path (i.e ttyUSB0). does it exist a command which does this?

    about dmesg and udevadm info they are too verbose.

    I would rather to have a simpler output, the best would be to append just the device file path to the output of lsusb, something like:

    Bus 003 Device 003: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter /dev/ttyUSB0

    • chili555
      chili555 over 5 years
      Please try: lsusb -t
    • aster94
      aster94 over 5 years
      output without port: /: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 480M |__ Port 1: Dev 4, If 0, Class=Vendor Specific Class, Driver=ch341, 12M
    • Thomas Ward
      Thomas Ward over 5 years
      Are you looking for the actual physical port, or the corresponding ttyUSB device path? That isn't the "port", that's the "Device file path"
    • aster94
      aster94 over 5 years
      yes, my mistake (due to ignorance) i am editing my question
    • Katu
      Katu over 5 years
      I think dmesg -w is the easy way but check this answer for more options stackoverflow.com/questions/2530096/…