mkdir if not exists

Last Updated 2022-12-18

To create new directories if they do not exist and ignore the command if they do (no error message) use: 

 $ mkdir -p 

The [.inline-code]-p[.inline-code] flag also allows for subdirectories to be created, if they do not already exist. For example:

 $ mkdir -p foo/bar/test

will create the folder “test” within the folder “bar” within the folder “foo”. 

[#mkdir-vs-mkdir-p]When should I use [.inline-code]mkdir[.inline-code] vs [.inline-code]mkdir -p[.inline-code]?[#mkdir-vs-mkdir-p]

[.inline-code]mkdir -p[.inline-code] can handle creating subdirectories in one command. An additional feature of adding the [.inline-code]-p[.inline-code] flag is the lack of an error message when the directory already exists. For example, to create subdirectories using [.inline-code]mkdir[.inline-code] you would need to do:

 $ mkdir foo #create the folder “foo”
 $ cd foo #navigate into the folder “foo”
 $ mkdir bar #create the folder “bar” inside the folder “foo”

adding the [.inline-code]-p[.inline-code] flag allows you to create the subdirectory bar inside the directory foo (even if foo doesn’t exist yet) in one line:

 $ mkdir -p foo/bar #creates the folder foo and the folder bar inside foo

[#ignore-directory-if-exists]Using [.inline-code]mkdir -p[.inline-code] to ignore a directory if it already exists[#ignore-directory-if-exists]

Without [.inline-code]-p[.inline-code], [.inline-code]mkdir[.inline-code] has this behavior:

 $ mkdir foo #create foo
 $ mkdir foo #foo exists now, command errors out

will return the error, “File exists”. But, when used in conjunction with the [.inline-code]-p[.inline-code] flag, the command to create a new directory is instead ignored, with no error returned:

 $ mkdir -p foo #create foo
 $ mkdir -p foo #foo exists now, command is ignored

So [.inline-code]mkdir -p[.inline-code] is useful if you want to make subdirectories quickly, and when using the [.inline-code]mkdir[.inline-code] command in situations where you want the command to be ignored (no error) if the directory already exists – for example, when using [.inline-code]mkdir[.inline-code] in combination with other commands to create efficient pipelines for data writing and storage.

[#create-directory-if-missing]Create directory if missing while using [.inline-code]cp[.inline-code][#create-directory-if-missing]

[.inline-code]mkdir -p[.inline-code] can be useful in combination with other commands like [.inline-code]cp[.inline-code] (copy). Combining the [.inline-code]mkdir[.inline-code] and [.inline-code]cp[.inline-code] commands is a powerful way to create directories that don’t exist and copy them over all in one go:

 $ mkdir -p  && cp 

where the && operator combines the two commands, and the [.inline-code]cp[.inline-code] command stands for “copy”.