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.
Categories: Uncategorized




Hey, that’s what I have searched for a long time. Thanks, man. It works!
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.
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
Are md5sum and sed really necessary? Could you not just do a diff between OLDstate.txt and NEWstate.txt?
[ -z $(diff OLDstate.txt NEWstate.txt) ] && sdparm –flexible –command=stop /dev/$1
Translation: Spin down when diff returns a zero-length string on comparing OLDstate.txt and NEWstate.txt. This gets rid of a few lines of code and reduces external dependencies.
Awesome, just what I was looking for since my internal SATA HD’s would not spin down anymore after upgrade to ubuntu 10.04