Bash – Is checking for exit status other than 0 after a `command || return` unreachable

bashshell-script

I found the following patch of code:

function some_fun() {    
#[...]
    [ -d ${MKAPP_BUILDDIR}/tmp ] || mkdir ${MKAPP_BUILDDIR}/tmp || return 1

    if [ $? -ne 0 ]; then   # never true?
            mount -t tmpfs none ${MKAPP_BUILDDIR}/tmp || return 1
    fi
}

As far as I understand it, it checks if there is a tmp directory in the build directory and, if that is not the case, tries to create it. If that also fails it exits the functions with status code 1.

If that is the case, wouldn't checking for an unsuccessful exit code in the if statement below be pointless? There can't be an unsuccessful command before, because it would've led to the function returning and the if statement never being processed.

Am I correct in thinking that, or is the syntax playing tricks on me?

I'm using bash, btw.

Best Answer

Yes you are correct. The return procedure will exit from the function to the originating caller in the script with an exit status of 1.

Therefore the mount command will never get processed.

To resolve this, just strip the if .. then statement from the mount command:

[ -d ${MKAPP_BUILDDIR}/tmp ] || mkdir ${MKAPP_BUILDDIR}/tmp || return 1

mount -t tmpfs none ${MKAPP_BUILDDIR}/tmp || return 1

Therefore if the directory cannot be created: exit with status of 1.
If the creation is successful, then run the mount command.

Related Question