Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: Bash: what does mkdir return

Tags:

linux

bash

mkdir

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?

like image 445
Tu Hoang Avatar asked Aug 22 '11 22:08

Tu Hoang


2 Answers

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
like image 142
Owen Avatar answered Oct 03 '22 07:10

Owen


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

like image 26
sehe Avatar answered Oct 03 '22 08:10

sehe