问题描述
我正在编写一个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.
是否有关于如何最好地做到这一点的想法?
Any thoughts on how best to 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 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.
如果您希望在父目录不存在时发生错误,并且要在目录不存在时创建该目录,则可以 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!