How to Create Multiple Nested Directories in Shell Using Mkdir?

Find out ways to create multiple directories / sub-directories at once using mkdir in shell

In this article, we will look at ways to create multiple directories / sub-directories at once using mkdir in terminal. We will only be focusing on ways that are common and well-supported across different types of shells (such as bash, zsh, fish, etc.).

For all the examples in the article, we will be considering the following directory structure:

public/

Please note the use of -p flag with mkrdir in the examples; it is used to create intermediate directories as required — i.e. it will automatically produce the parent directories that do not exist.

Using Space-Separated Directory Names

You could cd into the directory where you want to create the sub-directories and specify space-separated multiple directories / sub-directories with mkdir like so:

cd public
mkdir -p static/css static/js views/html

This will produce the following output:

public/
..└── static/
....└── css
....└── js
..└── views/
....└── html

Specifying Directories by Grouping

Grouping can be a great way to avoid repetition, but it comes at a cost of reduced readability. With mkdir you can group the directories you wish to create by enclosing comma-separated directory names (without spaces) inside curly braces. Consider, for example:

mkdir -p public/{static/{cs,js},views/html}

The above example will produce the following output:

public/
..└── static/
....└── css
....└── js
..└── views/
....└── html

Creating Multiple Directories With Spaces in the Name

From the previous examples, you may be wondering how to create a directory with space in the name. To do that, you have two options:

  1. Escape the space (for example, hello\ world)
  2. Use single or double quotes (for example, 'hello world')

Examples:

Let's suppose we want to create the following directory structure:

public/
..└── static/
....└── css test
....└── js test
..└── views/
....└── html

We could achieve that in the following ways:

Using Space-Separated Directory Names:

cd public
mkdir -p static/'css test' static/js\ test views/html

Specifying Directories by Grouping:

mkdir -p public/{static/{'cs test',js\ test},views/html}

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.