Linux Commands

Mkdir Recursive

“In Linux, mkdir is a dedicated command for creating new directories. By default, the command creates one-level directories. However, with some additional flags, it can create multi-level directories. The mkdir command also allows you to set permissions for the directories.”

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:

$ mkdir <dir_name>

You can verify if the action was successful:

$ ls -l

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:

$ mkdir --verbose <dir_name>

We can also create multiple directories using a single mkdir command:

$ mkdir --verbose <dir_1> <dir_2> <dir_3>

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.

$ mkdir <multi_layer_dir>

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:

$ mkdir --verbose --parents layer_a/layer_b/layer_c/

With the help of the tree command, we can visualize the structure:

$ tree layer_a/

Typing the full name of the mkdir flags is a bit tedious, right? We can combine –verbose and –parents in the following manner:

$ mkdir -vp layer_a/layer_b/layer_c/

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:

$ mkdir -pv layer_a/{1,2,3}/layer_c

We can use the tree command for better visualization of the directory hierarchy:

$ tree layer_a/

Final Thoughts

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:

$ man mkdir

Happy Computing!

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.