Home > Uncategorized > Howto: Automatically spin down external usb hard drives in Ubuntu

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.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
Categories: Uncategorized Tags:
  1. November 20th, 2009 at 07:14 | #1

    Hey, that’s what I have searched for a long time. Thanks, man. It works!

  2. January 7th, 2010 at 23:28 | #2

    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.

  3. March 2nd, 2010 at 19:31 | #3

    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

  4. Phil
    April 25th, 2010 at 10:44 | #4

    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.

  5. June 20th, 2010 at 12:59 | #5

    Awesome, just what I was looking for since my internal SATA HD’s would not spin down anymore after upgrade to ubuntu 10.04

  1. No trackbacks yet.