Linux: bash: what mkdir returns

I want to write a simple check when running mkdir to create a directory. First, it checks if an existing directory exists, if it does, it will simply skip. If dir does not exist, it starts mkdir, if mkdir fails (this means that the script cannot create the directory because it does not have sufficient privileges), it will complete.

Here 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, 2nd, if it seems, is not working correctly (I catch 0 as the return value for a successful mkdir). So, how to write the 2nd, if? and what makes mkdir successful as well as failure?

+6
source share
3 answers

Work result

 `mkdir -p "$FINALPATH"` 

It is not a return code, but an exit from the program. $? 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 
+13
source

The shorter it will be

  mkdir -p "$FINALPATH" || echo failure 

also idiomatic:

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

Similarly, you can while .....; do ....; done while .....; do ....; done while .....; do ....; done or until ......; do ......; done until ......; do ......; done

+2
source

For completeness only, you can exit by issuing:

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

Brackets are required, otherwise exit 1 will be executed in both cases.

Or you can create an interrupt function, for example:

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

And then just call it by issuing:

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

Edited by:

  • Brackets, not brackets, in brackets only exit the subshell. (Thanks @Charles Duffy)
  • Function to record message and exit
+2
source

Source: https://habr.com/ru/post/895636/


All Articles