bash 如果不存在,则仅 mkdir

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18622907/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:08:49  来源:igfitidea点击:

Only mkdir if it does not exist

bashunix

提问by More Than Five

In my bash script I do:

在我的 bash 脚本中,我这样做:

mkdir product;

When I run the script more than once I get:

当我不止一次运行脚本时,我得到:

mkdir: product: File exists

In the console.

在控制台中。

So I am looking to only run mkdir if the dir doesn't exist. Is this possible?

所以我希望只在目录不存在的情况下运行 mkdir 。这可能吗?

回答by konsolebox

Do a test

做一个测试

[[ -d dir ]] || mkdir dir

Or use -p option:

或者使用 -p 选项:

mkdir -p dir

回答by sr01853

if [ ! -d directory ]; then
  mkdir directory
fi

or

或者

mkdir -p directory

-pensures creation if directorydoes not exist

-p如果directory不存在,则确保创建

回答by Andy Lester

Use mkdir's -poption, but note that it has another effect as well.

使用 mkdir 的-p选项,但请注意它还有另一个效果。

 -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each oper-
         and must already exist.  On the other hand, with this option specified, no error will be reported if a directory
         given as an operand already exists.  Intermediate directories are created with permission bits of rwxrwxrwx
         (0777) as modified by the current umask, plus write and search permission for the owner.

回答by Paul Rubel

mkdir -p

mkdir -p

-p, --parents no error if existing, make parent directories as needed

-p, --parents 如果存在没有错误,根据需要创建父目录

回答by Rahul Tripathi

Try using this:-

尝试使用这个:-

mkdir -p dir;

NOTE:-This will also create any intermediate directories that don't exist; for instance,

注意:-这也将创建任何不存在的中间目录;例如,

Check out mkdir -p

查看mkdir -p

or try this:-

或试试这个:-

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$Message" 1>&2
fi