In this guide, we will look at using mkdir to create directories recursively.
Creating Directories Using mkdir
First, let’s look at the most basic way of using mkdir. The following command will create a directory with the name given:
You can verify if the action was successful:
Alternatively, we can enable the verbose mode with mkdir. This way, the mkdir command will print the action’s result. To enable the verbose mode, use the flag -v or –verbose:
We can also create multiple directories using a single mkdir command:
However, mkdir doesn’t allow creating a multi-layer directory by default. If attempted, mkdir will show an error that it can’t find the parent directory.
Creating Directories Recursively
To create a multi-layer directory, mkdir comes with the flag -p or –parents. In this mode, mkdir will return no error if the parent directory exists. If the parent directory doesn’t exist, it will create it instead.
Let’s try this option out. In the following example, we’re creating a three-layer directory:
With the help of the tree command, we can visualize the structure:
Typing the full name of the mkdir flags is a bit tedious, right? We can combine –verbose and –parents in the following manner:
Creating Multiple Child Directories With Brace Expansion
If you’re using bash, we can also take advantage of the brace-expansion feature to create multi-layered directories. Have a look at the following example:
We can use the tree command for better visualization of the directory hierarchy:
In this guide, we explored using mkdir to create directories recursively. For demonstration, we instructed mkdir to create multi-layer directories using the –parents flag. Per instruction, mkdir recursively created the child directories. Learn more about using the mkdir command.
The man page is always a great source of in-depth info and explanations: