(switch) Off with its heads – part II

I used the info explained in the first part of the article (Off with her heads) to create a script to power off usb devices.
Use at your own risk and enjoy 😉

#!/bin/bash
# author Roberto Polli robipolli@gmail.com

USB_ID=${1/://}
SET_VALUE=$2

usage(){
echo "usage: $0 USB_ID [on|off]";
echo "Power on or off the usb port associated with a given id"
echo ""
echo "This command is useful for nice power off usb devices"
echo "like storage drives"
exit 2;
}

if [ -z "$USB_ID" ]; then
usage;
fi
case $SET_VALUE in
on) SET_VALUE="on";
;;
off) SET_VALUE="suspend"
;;
*)
echo "bad SET_VALUE: $SET_VALUE. Valid values: [on|off]"
usage
;;
esac

LEVEL_COMMAND=$(/usr/bin/find /sys/bus/usb/devices/usb*/ -maxdepth 2 -name uevent \
-exec sh -c 'grep -q '$USB_ID' {} && echo `dirname {}`/power/level' \; \
2>/dev/null )

if [ -z "$LEVEL_COMMAND" ]; then
echo "no devices found with id $USB_ID"
exit 0;
fi
i=0
for file in $LEVEL_COMMAND; do
if [ -f $file ]; then
if [ $i -gt 1 ]; then
echo "$file: I'm cowardly refusing to operate on more than one usb device"
else
STATUS=`cat $file`
if [ "$STATUS" = "$SET_VALUE" ]; then
echo "$file: value already set to $STATUS"
else
echo "$SET_VALUE" | tee $file
exit $?
fi
fi
else
echo "$file: no such file"
fi
done