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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With