[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Resetting a USB port in Debian 10



On Thu, May 19, 2022 at 08:54:52AM +0100, Tixy wrote:
> To find the device ID my bash script scans the USB serial numbers
> looking for the one I'm interested in...
> 
>    pushd /sys/bus/usb/drivers/usb >/dev/null
>    for f in **/serial
>    do
>    	if [ "$(cat $f)" = MY_SERIAL_NUMBER ]; then
>    		ID=${f%%/*}
>    	fi
>    done
>    popd >/dev/null
>    
>    if [ "$ID" = "" ]; then
>    	echo "Can't find device"
>    	exit 1
>    fi
>    
> There's no doubt better ways of doing the above, but it works for me.
> (Looking at it now I'd get rid of the pushd/popd by using an extra
> string splice operation and that use of ** probably needs something
> doing to it to cope with spaces in paths)

1) For ** to work, you need to do "shopt -s globstar" somewhere before it.

Other issues:

2) You didn't check the success of your pushd.  If it fails, you could
   theoretically run the rest of the script from the wrong directory.

3) "$f" should be quoted, in "$(cat "$f")".  Or, if you'd like to avoid
   forking a cat(1) for every USB serial device, you could do something
   like:

   for f in **/serial
   do
      read -r serial < "$f"
      if [ "$serial" = MY_SERIAL_NUMBER ]; then
         id=${f%%/*}
      fi
   done

4) There's no reason to keep reading if you've already found the desired
   id, so you could add a "break" right after the id=${...} part.


Reply to: