Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script to test whether a directory exists and if not create it?

I am trying to create a script to detect whether a directory exists, and if it does not, to create it.

How can I do that?

I did some digging and found a clue:

test -d directory

...will return true or false depending on whether the directory exists or not.

But how do I tie this together with mkdir?

like image 297
Nathan Osman Avatar asked May 30 '10 04:05

Nathan Osman


People also ask

What does != Mean in shell script?

There are 6 types of valid relational operators in shell scripting − == operator is the operator that equates the values of two operators. It returns true if the values are equal and returns false otherwise. != operator is the operator that equates the values of two operators and check for their inequality.


2 Answers

mkdir -p $directory should do what you want. The -p option will create any necessary parent directories. If $directory already exists as a directory, the command does nothing, and succeeds. If $directory is a regular file, it will remain untouched, and the command will fail with an appropriate error message.

Without the -p option to mkdir, the test ... || mkdir ... strategy can fail if $directory contains a '/', and some component of that path doesn't already exist. The test is superfluous anyway, since mkdir does the same test internally.

like image 172
Jim Lewis Avatar answered Sep 21 '22 00:09

Jim Lewis


test ... || mkdir ...
like image 31
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 00:09

Ignacio Vazquez-Abrams