The Difference between mkdir
and mkdir -p
The mkdir
command in Linux is used to create new directories. However, there is a subtle difference between using mkdir
and mkdir -p
.
mkdir
Command
The basic mkdir
command is used to create a single directory. For example, if you want to create a directory named "example" in the current working directory, you can use the following command:
mkdir example
This command will create a new directory named "example" in the current working directory.
However, if the parent directory of the directory you want to create does not exist, the mkdir
command will fail and return an error. For example, if you try to create a directory named "example/test" and the "example" directory does not exist, the command will fail:
mkdir example/test
mkdir: cannot create directory 'example/test': No such file or directory
mkdir -p
Command
The mkdir -p
command is used to create a directory, including any necessary parent directories. This means that if the parent directory does not exist, mkdir -p
will create it automatically.
For example, if you want to create a directory named "example/test" and the "example" directory does not exist, you can use the mkdir -p
command:
mkdir -p example/test
This command will create the "example" directory and then create the "test" directory inside it.
The mkdir -p
command is particularly useful when you need to create a complex directory structure with multiple levels of subdirectories. Instead of having to create each directory individually, you can use mkdir -p
to create the entire structure in a single command.
Here's a visual representation of the difference between mkdir
and mkdir -p
using a Mermaid diagram:
In summary, the main difference between mkdir
and mkdir -p
is that mkdir -p
can create the entire directory structure, including any necessary parent directories, while mkdir
can only create a single directory at a time.