开发者

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 开发者_Go百科(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?


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜