Pages

Wednesday, December 21, 2016

Linux script sample 1. A good example of for loop, sed, cut, if

==============
usb-device.sh
==============
Script for checking usb devices.The actual logic not importatnt - just a good example of for loop, sed, cut, etc...

for dir in `find /proc/bus/usb -type d -regex .+[0-9]+`
do
   bus=`basename $dir` 
   cntl=`echo $bus | sed 's/^0*/usb/' `
   interface="0"

   for device in `lsusb -s $bus: |cut -d' ' -f4|sed -e 's/://' | tr '\n' ' '`
   do
      devicetype=`lsusb -v -s $bus:$device | grep bDeviceClass | sed -e 's/^ *bDeviceClass \+[0-9]\+ //'`
      manufacturer=`lsusb -v -s $bus:$device | grep iManufacturer | sed -e 's/^ *iManufacturer \+[0-9]\+ //'`
      interfaceSubClass=`lsusb -v -s $bus:$device | grep bInterfaceSubClass | sed -e 's/^ *bInterfaceSubClass \+[0-9]\+ //'`
      if [ "$interfaceSubClass" = "SCSI" ]; then
          i=1
          for interface in `lsusb -v -s $bus:$device | grep bInterfaceNumber | sed -e 's/^ *bInterfaceNumber \+//'`
          do
              product=`lsusb -v -s $bus:$device | grep iInterface | sed -e 's/^ *iInterface \+[0-9]\+ //' | head -n $i | tail -n 1`
              if [ -z "$product" ]; then 
                  product=`lsusb -v -s $bus:$device | grep iProduct | sed -e 's/^ *iProduct \+[0-9]\+ //' | head -n $i | tail -n 1`
              fi

              devicetype=`lsusb -v -s $bus:$device | grep bInterfaceClass | sed -e 's/^ *bInterfaceClass \+[0-9]\+ //' | head -n $i | tail -n 1`

              echo -e "$cntl\t$bus-$device-$interface\t$devicetype\t$product\t$manufacturer"

              i=`expr $i + 1`
          done
      else
          if [ "$interfaceSubClass" = "SCSI" ]; then
              product=`lsusb -v -s $bus:$device | grep iProduct | sed -e 's/^ *iProduct \+[0-9]\+ //'`
              #echo -e "$cntl\t$bus-$device\t$devicetype\t$product"
              echo -e "$cntl\t$bus-$device-$interface\t$devicetype\t$product\t$manufacturer"
          fi
      fi
   done
done

No comments:

Post a Comment