views:

536

answers:

2

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?

+7  A: 

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
Andy Ross
knittl
Well, that's sorta situational. It's easy to imagine a script wanting to continue, but leave any error messages in the log stream.
Andy Ross
You can make this a little faster by using the pseudo-command `:` (a shell builtin) instead of /bin/true (which creates a new process). That is, use "`umount .... || :`"
Gordon Davisson
+2  A: 

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).

Michał Górny