(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

(switch) Off with her heads

How to switch off your usb external drive after umount and stop its spinning heads?

The following article gives some hints, which I summarize here.

http://www.lesswatts.org/projects/devices-power-management/usb.php

1) find the device to switch off (eg. the USB Mouse)

root@rpolli:/sys/bus/usb/devices# lsusb

Bus 004 Device 005: ID 046d:c050 Logitech, Inc. RX 250 Optical Mouse

Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

2) Go to directory

# cd /sys/bus/usb/devices/4-2

3) check that the device is the one we need

# cat product

USB-PS/2 Optical Mouse

4) disable it :D

# echo suspend > power/level

HTH