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

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


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 to mkdir , this check is useless, because this is what does in the first place. Just write:

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

and thats it.


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

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.

链接地址: http://www.djcxy.com/p/97118.html

上一篇: rm,cp,mv命令的参数列表太长错误

下一篇: 如何使用Bash创建一个文件夹,如果它尚不存在?