Automatic Disk Drive Mount On Folder Access

This script is switching the power of an external hard drive on demand and is mounting the drive automatically. It's also unmounting the drive if not accessed any more and is switching the power off.

I use a radio controlled plug to switch a USB hard drive on and off. To control the hard drive the script is sending a command to Hominaut, but you can also use any other solution based on FHEM or other home automation system.

Lets explain the script in few steps
  1. I use 'lsof -d /media/usb_drive' to detect if some process is accessing the folder /media/usb_drive. Usually lsof returns nothing.
  2. If I access this folder in any way (e.g samba, http, owncloud) then the script is sending a command to Hominaut.
  3. Hominaut is sending a radio signal to the plug. The Plug gives power to the hard drive is starting up.
  4. The script is mounting the hard drive. It tries again, if something goes wrong.
  5. The volume is mounted within seconds after access.
  6. When I leave the folder /media/usb_drive then the script tries to unmount the drive. It tries again and again.
  7. When umount was successful, then the scripts sends a request to Homienaut to swicth off the hard drive.

The script
# Automatic Disk Drive Mount On Folder Access
# Version 1
# Written by Andreas Tobola, October 2015,
# Scrip must be run as root to access all open files by any process


# start condition
umount $FOLDER

while [ true ]

    OPEN_FILES=`lsof +d $FOLDER -b -t | wc -l`
    if [ "$OPEN_FILES" -gt "0" ]; then
        # Folder is open. Mount volume if  not mounted yet.
        if [ "$LAST_STATE" -eq "0" ]; then
            echo Folder $FOLDER has been accessed
            curl ''
            if [ "$?" -eq "0" ]; then
                echo Volume power on request sent
                sleep 4  # Give the hard drive x seconds to get ready
                mount $FOLDER
                if [ "$?" -eq "0" ]; then
                    # Check if volume is mounted and then wait otherwise try again
                    echo Volume mounted
                    sleep 10
        if [ "$LAST_STATE" -eq "1" ]; then
            echo Folder $FOLDER is not accessed by any process anymore
            umount $FOLDER
            if [ "$?" -eq "0" ]; then
                echo Volume umounted
                curl ''              
                echo Volume switched off
                sleep 10
    sleep 1


Siehe auch
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki