Tu Hoang
Tu Hoang

Reputation: 4712

Linux: Bash: what does mkdir return

I want to write a simple check upon running mkdir to create a dir. First it will check whether the dir already exists, if it does, it will just skip. If the dir doesn't exist, it will run mkdir, if mkdir fails (meaning the script could not create the dir because it does not have sufficient privileges), it will terminate.

This is what I wrote:

if [ ! -d "$FINALPATH" ]; then
    if [[ `mkdir -p "$FINALPATH"` -ne 0 ]]; then
        echo "\nCannot create folder at $FOLDERPATH. Dying ..."
        exit 1
    fi
fi

However, the 2nd if doesn't seem to be working right (I am catching 0 as return value for a successful mkdir). So how to correctly write the 2nd if? and what does mkdir returns upon success as well as failure?

Upvotes: 7

Views: 23418

Answers (3)

DrBeco
DrBeco

Reputation: 11785

Just for completeness, you can exit by issuing:

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

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

Or you can create an abort function 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

Upvotes: 3

sehe
sehe

Reputation: 393487

The shorter way would be

 mkdir -p "$FINALPATH" || echo failure

also idiomatic:

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

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

Upvotes: 3

Owen
Owen

Reputation: 39366

The result of running

`mkdir -p "$FINALPATH"`

isn't the return code, but the output from the program. $? the return 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

Upvotes: 20

Related Questions