mkdir if not exists in linux/unix
June 25, 2020
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.
example
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

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
It would be helpful to demonstrate the command does not return an error if the directory DOES exist.
mkdir -p /tmp/newdir
echo $?
-> 0
mkdir /tmp/newdir
-> mkdir: cannot create directory ‘/tmp/newdir’: File exists
echo $?
-> 1
mkdir -p /tmp/newdir # Directory already exists.
echo $?
-> 0