Howto: Automatically spin down external usb hard drives in Ubuntu

Spinning down external usb hard drives in Ubuntu doesn’t allways happen automatically in Ubuntu. To force a spindown, you can issue the command
sync sdparm --flexible --command=stop /dev/sdX &>/dev/null
where you should replace the sdX entry by the correct name of your external hard drive (usually sdb, sdc or similar).
To do this automatically every 5 minutes, save the code below as e.g. ~/bin/spindown/spindown.sh.
# !/bin/sh # Get new state from diskstats NEWstate=$(cat /proc/diskstats | grep $1) echo $NEWstate > NEWstate.txt # compare md5 sums md5new=$(md5sum NEWstate.txt | sed 's/ .*//') md5old=$(md5sum OLDstate.txt | sed 's/ .*//') # if no changes, power down if [ "$md5new" = "$md5old" ]; then sdparm --flexible --command=stop /dev/$1 &>/dev/null fi # Write current state to file echo $NEWstate > OLDstate.txt
Then, add the entry
*/5 * * * * root sh /home/user/bin/spindown/spindown.sh sdX
to the cron file /etc/crontab. The script automatically checks to see if the drive has been active for the last 5 mins. If not, it forces a spindown.




Hey, that’s what I have searched for a long time. Thanks, man. It works!
Soeren Beerbaum
20 Nov 09 at 7:14 am
Great post - works really well. Thanks.
If anybody’s interested, I also added some code at the top of the script to check that it is being run as root…
if [ "$(id -u)" != "0" ]; then
echo “This script must be run as root” 1>&2
exit 1
fi
Obviously this is not needed for cron, but useful for testing etc.
Andy
7 Jan 10 at 11:28 pm
hey!
many thanks for the script.
for external usb drive compatibility i added the following lines.
#convert UUID to ID
disk=$(blkid | grep $1 | cut -c 6-9)
#check if the disk uuid, or pieces of it were ok
if [ ! -n $disk ]; then
echo “no such disk - disk!”
exit 1
fi
cheers
patrick
2 Mar 10 at 7:31 pm