Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mkdir only if a directory does not already exist?

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?

like image 358
Spike Williams Avatar asked Apr 27 '09 14:04

Spike Williams


People also ask

What happens to mkdir If directory already exists?

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.

Does mkdir overwrite existing directories?

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.

How do you create a directory if it doesn't exist in Python?

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.


1 Answers

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 
like image 54
Brian Campbell Avatar answered Sep 27 '22 18:09

Brian Campbell