3

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
  • Maybe the -l (ell) switch? See linux.die.net/man/8/umount – PerlDuck Oct 14 '18 at 8:53
  • 1
    I don't think the lazy umount option blocks the script from executing until it finishes – Askerman Oct 14 '18 at 8:57
  • 1
    @PerlDuck Using -l will get the umount command to succeed quickly and will prevent any more access to the file system from happening through the mount point. But any already open handles or current directories will keep using the file system, and it is a bit tricky to detect when exactly such usage has stopped. – kasperd Oct 14 '18 at 13:52
4

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'
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.