How to make umount wait, until a device is not busy?

I have a bash script file where I execute a bunch of commands.

#!/bin/bash
umount /media/hdd1
umount /media/hdd2
something1
something2

But since the comands later in the file work with the umounted HDD, I need to make sure the umount is successful before continuing.

I can of course check if the umount failed and just exit 1, but that is not ideal.

So basically, what I would like to do, is somehow make the umount command wait, until the device is not busy and then umount the HDD and continue executing the script.

It would thus work like this:

#!/bin/bash
umount /media/hdd1 # Device umounted without any problems continuing the script..
umount /media/hdd2 # Device is busy! Let's just sit around and wait until it isn't... let's say 5 minutes later whatever was accessing that HDD isn't anymore and the umount umounts the HDD and the script continues
something1
something2

Thank you.

3

1 Answer

I think the following script will do the job. It should be run with sudo (superuser permissions).

There is a function doer with a while loop, that checks with mountpoint if a device is mounted at the specified mount point, and if it is, tries to unmount it with umount. When the logical variable busy is false, the while loop is finished and the script can start 'doing some things'.

#!/bin/bash
function doer() {
busy=true
while $busy
do if mountpoint -q "$1" then umount "$1" 2> /dev/null if [ $? -eq 0 ] then busy=false # umount successful else echo -n '.' # output to show that the script is alive sleep 5 # 5 seconds for testing, modify to 300 seconds later on fi else busy=false # not mounted fi
done
}
########################
# main
########################
doer /media/hdd1
doer /media/hdd2
echo ''
echo 'doing something1'
echo 'doing something2'
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like