How to find all USB devices connected in Linux (Ubuntu)?

Issue

I have found a script somewhere, which partially does what I want it to:

#!/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/"* ]] && continue
        eval "$(udevadm info -q property --export -p $syspath)"
        [[ -z "$ID_SERIAL" ]] && continue
        echo "{'name': '/dev/$devname', 'id_serial': '$ID_SERIAL'}"
    )
done

But this way I am getting all connected devices:

{'name': '/dev/ttyACM3', 'id_serial': 'Arduino__www.arduino.cc__0043_74132343221092D0'}
{'name': '/dev/input/event16', 'id_serial': 'Logitech_USB_Receiver'}
{'name': '/dev/input/mouse2', 'id_serial': 'Logitech_USB_Receiver'}
{'name': '/dev/hidraw0', 'id_serial': 'Logitech_USB_Receiver'}
{'name': '/dev/usb/hiddev0', 'id_serial': 'Logitech_USB_Receiver'}
{'name': '/dev/input/event17', 'id_serial': 'Logitech_USB_Receiver'}
{'name': '/dev/hidraw1', 'id_serial': 'Logitech_USB_Receiver'}
{'name': '/dev/ttyACM0', 'id_serial': 'Lenovo_N5321_gw_41C01111111A76M0'}
{'name': '/dev/ttyACM1', 'id_serial': 'Lenovo_N5321_gw_41C0BAAAAD5A76M0'}
{'name': '/dev/ttyACM2', 'id_serial': 'Lenovo_N5321_gw_41C0B11111111110'}
{'name': '/dev/input/event15', 'id_serial': 'SunplusIT_INC._Integrated_Camera'}
{'name': '/dev/media0', 'id_serial': 'SunplusIT_INC._Integrated_Camera'}
{'name': '/dev/video0', 'id_serial': 'SunplusIT_INC._Integrated_Camera'}

How do I get only the /dev/tty* ones (not necessarily by using the same code)?

Solution

#!/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/"* ]] && continue
    [[ "$devname" != "tty"* ]] && continue

    eval "$(udevadm info -q property --export -p $syspath)"
    [[ -z "$ID_SERIAL" ]] && continue
    echo "{'name': '/dev/$devname', 'id_serial': '$ID_SERIAL'}"
done

This line:

[[ "$devname" != "tty"* ]] && continue

Will skip printing any device that does not start with tty.

Answered By – Will

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published