如果文件夹不存在,如何使用 Bash 创建文件夹?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4906579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Bash to create a folder if it doesn't already exist?
提问by mlzboy
#!/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?
这似乎不起作用。任何人都可以帮忙吗?
回答by Maxim Sloyko
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:
首先,在 bash 中“[”只是一个命令,它需要字符串“]”作为最后一个参数,所以右括号前的空格(以及“!”和“-d”之间需要两个单独的参数太)很重要:
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:
其次,由于您使用的是 -p switch to mkdir
,所以这个检查是没有用的,因为这是首先要做的。写就好了:
mkdir -p /home/mlzboy/b2c2/shared/db;
and thats it.
就是这样。
回答by kurumi
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 就可以了
mkdir -p /home/mlzboy/b2c2/shared/db
回答by Automatico
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 将抛出错误。要忽略错误,请写入:
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
-p, --parents no error if existing, make parent directories as needed
http://man7.org/linux/man-pages/man1/mkdir.1.html
回答by dogbane
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
回答by plesiv
Cleaner way, exploit shortcut evaluation of shell logical operators. Right side of the operator is executed only if left side is true.
更简洁的方式,利用 shell 逻辑运算符的快捷评估。仅当左侧为真时才执行运算符的右侧。
[ ! -d /home/mlzboy/b2c2/shared/db ] && mkdir -p /home/mlzboy/b2c2/shared/db
回答by ivy
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;