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 WILL give you an error if the directory already exists. mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.
1 Answer. Show activity on this post. The mkdir command will create any folders that do not exist in the specified path, unless extensions are disabled ( setLocal enableExtensions ) - regardless, it will not destroy a directory and create a new one with the same name.
To create a directory if not exist in Python, check if it already exists using the os. path. exists() method, and then you can create it using the os. makedirs() method.
Try 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
will create directories foo
, foo/bar
, and foo/bar/baz
if they don't exist.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With