Advertisement
Advertisement


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


Question

#!/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?

2011/02/05
1
182
2/5/2011 11:27:54 AM


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
2011/02/05

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

2018/11/16

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
2011/02/05

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
2014/06/09

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;
2011/02/05

Source: https://stackoverflow.com/questions/4906579
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]