156

What does the -p flag do in mkdir -p?

robinCTS
  • 4,367
user27449
  • 6,920

3 Answers3

196

The -p flag will create nested directories, but only if they don't exist already.

For example, suppose you have a directory /foo that you have write permissions for.

mkdir -p /foo/bar/baz  # creates bar and baz within bar under existing /foo

It is also an idempotent operation, because if you run the same command over again, you will not get an error, but nothing will be created.

d4nyll
  • 101
7

This -p flag allows a parent folder to be created along with the nested folder.

For example:

mkdir directory/nested_directory 

it would return the following error : mkdir: cannot create directory ‘directory/nested_directory’: No such file or directory

But if you use -p such as:

mkdir -p directory/nested_directory

It will create both directory and it's nested nested_directory folders successfully.

  • Welcome to Super User! Before answering an old question having an accepted answer (look for green ✓) ensure your answer adds something new or is otherwise helpful in relation to them. Here is a guide on [answer]. There is also a site [tour] and a [help]. – help-info.de Oct 05 '22 at 08:12
  • 1
    I think this answer adds clarity to the case when both the parent and the child directories do not exist. This is a superset of the "nested", child directory not existing. – Pablo Adames Sep 18 '23 at 15:49
1

It actually does two different things.

  1. No error if existing
    • Prints no errors like mkdir: cannot create directory ‘<dir>’: File exists
  2. Make parent directories as needed
    • You may create nested directories like mkdir -p dir1/dir2/dir3
    • The containing directories (in example: dir1, dir2) will be unaffected by file mode options (-m)
xamid
  • 111
  • 3