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

  • By Daniyal Hamid
  • January 18, 2020
  • Comments
In This Article

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}

There are of course many other ways to create multiple directories using mkdir, especially using different types of shells (such as bash, zsh, fish, etc.). If you have any to share with us, please let us know in the comments section.