How to use Bash to create a folder if it doesn't already exist?

BashDirectory

Bash Problem Overview


#!/bin/bash
if [!-d /home/mlzboy/b2c2/shared/db]; then
    mkdir -p /home/mlzboy/b2c2/shared/db;
fi;

This doesn't seem to work. Can anyone help?

Bash Solutions


Solution 1 - Bash

First, in Bash [ is just a command, which expects string ] as a last argument, so the whitespace before the closing bracket (as well as between ! and -d which need to be two separate arguments too) is important:

if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
  mkdir -p /home/mlzboy/b2c2/shared/db;
fi

Second, since you are using -p switch for mkdir, this check is useless, because this is what it does in the first place. Just write:

mkdir -p /home/mlzboy/b2c2/shared/db;

and that's it.

Solution 2 - Bash

There is actually no need to check whether it exists or not. Since you already wants to create it if it exists , just mkdir will do

mkdir -p /home/mlzboy/b2c2/shared/db

Solution 3 - Bash

Simply do:

mkdir /path/to/your/potentially/existing/folder

mkdir will throw an error if the folder already exists. To ignore the errors write:

mkdir -p /path/to/your/potentially/existing/folder

No need to do any checking or anything like that.


For reference:

-p, --parents no error if existing, make parent directories as needed http://man7.org/linux/man-pages/man1/mkdir.1.html

Solution 4 - Bash

You need spaces inside the [ and ] brackets:

#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ] 
then
    mkdir -p /home/mlzboy/b2c2/shared/db
fi

Solution 5 - Bash

Cleaner way, exploit shortcut evaluation of shell logical operators. Right side of the operator is executed only if left side is true.

[ ! -d /home/mlzboy/b2c2/shared/db ] && mkdir -p /home/mlzboy/b2c2/shared/db

Solution 6 - Bash

I think you should re-format your code a bit:

#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
    mkdir -p /home/mlzboy/b2c2/shared/db;
fi;

Solution 7 - Bash

Create your directory wherever

OUTPUT_DIR=whatever

if [ ! -d ${OUTPUT_DIR} ]
then
	mkdir -p ${OUTPUT_DIR}
fi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmlzboyView Question on Stackoverflow
Solution 1 - BashMaxim SloykoView Answer on Stackoverflow
Solution 2 - BashkurumiView Answer on Stackoverflow
Solution 3 - BashAutomaticoView Answer on Stackoverflow
Solution 4 - BashdogbaneView Answer on Stackoverflow
Solution 5 - BashplesivView Answer on Stackoverflow
Solution 6 - BashivyView Answer on Stackoverflow
Solution 7 - BashJasonView Answer on Stackoverflow