[Linux] How to create multiple Directories at once?

How to create multiple Directories using mkdir?

Sometimes we need to create multiple directories or a directory tree in Linux like while initializing the PHP or Java Project. In this post we will learn how to create them in a single command using mkdir.

Most of you who use linux are already aware of this feature of mkdir.

For example, What would you do If you need to create a project structure like given below:

The layman way would be creating myproject dir first then cd to myproject then creating src, tests and web directories one-by-one and so on. But there is also exists a nice or better way to do the job using the same mkdir command with -p flag.

The mkdir with -p flag first checks whether the given directory exists or not, If not then it create one else move forward. For example:

The command above will create both work directory and its subdirectory posts. It will first check If work directory exists, If not, will move forward and will try to create posts directory. It will not throw any error if a directory already exists, it will just skip it silently and move forward.

If you want to create multi sub directories at same level then you can specify them in {} seperated by comma ,. Like If we want to create both posts and archive directory under work directory mentioned above then the command will look like this:

Don’t put any spaces before or after commas and directory names otherwise you will be ended up with weird directory names like {posts or ,archieve.

Now lets create PHP project directory structure mentioned above in single command:

Bingo!! Now if you run tree command for myproject then you will see the directory structure created like this:

Congrats!! We have just successfully learned a handsome technique to create multiple directories in one shot.
We will see some other trick soon in the further posts. Till then Happy Coding!!!

Leave a Reply

Your email address will not be published. Required fields are marked *