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

Viewed 21715

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?

4 Answers

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"
Related