Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to test for failure of mkdir command?

I'm writing a bash script and want to do robust error checking in it.

The exit status code for mv to make it fail is easy to simulate a failure. All you have to do is move a file that doesn't exist, and it fails.

However with mkdir I want to simulate it failing. mkdir could fail for any number of reasons, problems with the disk, or lack of permissions, but not sure how to simulate a failure.

like image 334
Edward Avatar asked May 19 '13 09:05

Edward


2 Answers

Just use

mkdir your_directory/
if [ $? -ne 0 ] ; then
    echo "fatal"
else
    echo "success"
fi

where $? stands for the exit code from the last command executed.

To create parent directories, when these don't exist, run mkdir -p parent_directory/your_directory/

like image 166
Uroc327 Avatar answered Sep 21 '22 23:09

Uroc327


if ! mkdir your_directory 2>/dev/null; then
    print_error
    exit
fi

or

mkdir your_directory 2>/dev/null || { print_error; exit; }
like image 23
Adrian Frühwirth Avatar answered Sep 20 '22 23:09

Adrian Frühwirth