仅当目录不存在时才如何mkdir? [英] How to mkdir only if a directory does not already exist?

查看:110
本文介绍了仅当目录不存在时才如何mkdir?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Shell脚本以在AIX上的KornShell(ksh)下运行.我想使用mkdir命令创建目录.但是该目录可能已经存在,在这种情况下,我不想执行任何操作.因此,我想测试该目录不存在,或者抑制当尝试创建现有目录时mkdir引发的文件存在"错误.

I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the mkdir command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that mkdir throws when it tries to create an existing directory.

我怎样才能最好地做到这一点?

How can I best do this?

推荐答案

尝试 mkdir -p :

mkdir -p foo

请注意,这还将创建所有不存在的中间目录;例如,

Note that this will also create any intermediate directories that don't exist; for instance,

mkdir -p foo/bar/baz

将创建目录foofoo/barfoo/bar/baz(如果不存在).

will create directories foo, foo/bar, and foo/bar/baz if they don't exist.

一些实现(例如GNU mkdir)将mkdir --parents作为更易读的别名,但这在POSIX/Single Unix Specification中未指定,并且在macOS,各种BSD和各种商业Unix等许多常见平台上不可用,因此应该避免.

Some implementation like GNU mkdir include mkdir --parents as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.

如果您希望在父目录不存在时发生错误,并且要在目录不存在时创建该目录,则可以

If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can test for the existence of the directory first:

[ -d foo ] || mkdir foo

这篇关于仅当目录不存在时才如何mkdir?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆