仅当目录不存在时如何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