仅当目录不存在时如何 mkdir? [英] How to mkdir only if a directory does not already exist?
问题描述
我正在编写一个在 AIX 上的 KornShell (ksh) 下运行的 shell 脚本.我想使用 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
将创建目录 foo
、foo/bar
和 foo/bar/baz
如果它们不存在.
will create directories foo
, foo/bar
, and foo/bar/baz
if they don't exist.
一些像 GNU mkdir
的实现包括 mkdir --parents
作为一个更易读的别名,但这在 POSIX/Single Unix 规范中没有指定,并且在许多常见的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.
如果你想在父目录不存在时报错,如果目录不存在就想创建目录,那么你可以test
先为目录是否存在:
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屋!