Shell – Mounting and unmounting in same shell script results in error

mountshellshell-scripttarunmounting

I need to mount a volume, tar the contents of the mounted volume and unmount that mounted volume, in a single shell script.

So I coded as,

$ cat sample.sh
sudo mount -o loop Sample.iso /tmp/mnt
cd /tmp/mnt
tar-cvf /tmp/sample.tar *
sudo umount /tmp/mnt

I got the error umount: /tmp/mnt: device is busy.

So I checked the

$ lsof /tmp/mnt

It outputs the current "sh" file. So I convinced myself, /tmp/mnt is busy in the current script (in this case, sample.sh).

Is there any way around for (mount, tar, unmount) in the same script ?

P.S : I'm able to unmount the /tmp/mnt volume once the script finishes.

Best Answer

You need to exit the directory to unmount it, like this:

#!/bin/bash
sudo mount -o loop Sample.iso /tmp/mnt
cd /tmp/mnt
tar -cvf /tmp/sample.tar *
#Got to the old working directory. **NOTE**: OLDPWD is set automatically.
cd $OLDPWD
#Now we're able to unmount it. 
sudo umount /tmp/mnt

That is it.

Related Question