mkdir if not exists in linux/unix

mkdir creates a directory if it does not exist. We can use the mkdir -p option.

mkdir -p option

  • Create intermediate directories as required.
  • If this option is not specified, the full path prefix of each operand must already exist.
  • On the other hand, with this option specified, no error will be reported if a directory given as an operand already exists.
  • Intermediate directories are created with permission bits of rwxrwxrwx (0777) as modified by the current umask, plus write and search permission for the owner.

mkdir -p syntax

mkdir -p foo/bar/baz

will create directories foo, foo/bar, and foo/bar/baz if they don’t exist.


In the following example, we will use the mkdir command -p option to create a multi-level directory that does not exist.

➜  mkdir -p foo/bar/baz
mkdir if not exists

We execute the “mkdir -p foo/bar/baz” command again. You will find that the command will not report any errors.

Next we use the mkdir -p option to create a directory named “baz2” under the directory “foo/bar“.

➜  mkdir -p foo/bar/baz2

ok. Created successfully.

So, when we do not confirm whether the directory exists, we can use the mkdir -p option to create it when the directory does not exist.

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *