[ACCEPTED]-Linux: Bash: what does mkdir return-mkdir

Accepted answer
Score: 19

The result of running

`mkdir -p "$FINALPATH"`

isn't the return code, but 2 the output from the program. $? the return 1 code. So you could do

if mkdir -p "$FINALPATH" ; then
    # success
else
    echo Failure
fi

or

mkdir -p "$FINALPATH"
if [ $? -ne 0 ] ; then
    echo Failure
fi
Score: 3

The shorter way would be

 mkdir -p "$FINALPATH" || echo failure

also idiomatic:

 if mkdir -p "$FINALPATH"
 then
      # .....
 fi

Likewise 1 you can while .....; do ....; done or until ......; do ......; done

Score: 3

Just for completeness, you can exit by issuing:

mkdir -p "$FINALPATH" || { echo "Failure, aborting..." ; exit 1 ; }

Braces 3 are necessary, or else exit 1 would execute in 2 both cases.

Or you can create an abort function 1 like:

errormsg()
{
    echo "$1"
    echo Aborting...
    { exit 1 ; }
}

And then just call it by issuing:

mkdir -p "$FINALPATH" || errormsg "Failure creating $FINALPATH"

Edited:

  • Braces, not parenthesis, as parenthesis only exit the subshell. ( Thanks @Charles Duffy )
  • A function to write a message and exit

More Related questions