Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Script - umount a device, but don't fail if it's not mounted?

I'm writing a bash script and I have errexit set, so that the script will die if any command doesn't return a 0 exit code, i.e. if any command doesn't complete successfully. This is to make sure that my bash script is robust.

I have to mount some filesystems, copy some files over, the umount it. I'm putting a umount /mnt/temp at the start so that it'll umount it before doing anything. However if it's not mounted then umount will fail and stop my script.

Is it possible to do a umount --dont-fail-if-not-mounted /mnt/temp? So that it will return 0 if the device isn't mounted? Like rm -f?

like image 624
Amandasaurus Avatar asked Sep 04 '09 10:09

Amandasaurus


People also ask

How do you check if a directory is mounted or not?

Using the mount Command One way we can determine if a directory is mounted is by running the mount command and filtering the output. The above line will exit with 0 (success) if /mnt/backup is a mount point. Otherwise, it'll return -1 (error).

How do you check if a device is mounted on Linux?

You need to use any one of the following command to see mounted drives under Linux operating systems. [a] df command – Shoe file system disk space usage. [b] mount command – Show all mounted file systems. /proc/mounts or /proc/self/mounts file – Show all mounted file systems.


4 Answers

Assuming that your umount returns 1 when device isn't mounted, you can do it like that:

umount … || [ $? -eq 1 ]

Then bash will assume no error if umount returns 0 or 1 (i.e. unmounts successfully or device isn't mounted) but will stop the script if any other code is returned (e.g. you have no permissions to unmount the device).

like image 32
Michał Górny Avatar answered Sep 29 '22 07:09

Michał Górny


The standard trick to ignore the return code is to wrap the command in a boolean expression that always evaluates to success:

umount .... || /bin/true
like image 115
Andy Ross Avatar answered Sep 29 '22 07:09

Andy Ross


Ignoring exit codes isn't really safe as it won't distinguish between something that is already unmounted and a failure to unmount a mounted resource.

I'd recommend testing that the path is mounted with mountpoint which returns 0 if and only if the given path is a mounted resource.

This script will exit with 0 if the given path was not mounted otherwise it give the exit code from umount.

#!/bin/sh

if mountpoint -q "$1"; then
  umount "$1"
fi

You an also do it as a one liner.

! mountpoint -q "$mymount" || umount "$mymount"
like image 21
Dev Avatar answered Sep 28 '22 07:09

Dev


I just found the ":" more use ful and wanted a similar solution but let the script know whats happening.

umount ...... || { echo "umount failed but not to worry" ; : ; } 

This returns true with the message, though the umount failed.

like image 45
benki Avatar answered Sep 26 '22 07:09

benki