00_lead_image_creating_subdirectories_wih_one_command

If you want to create a directory containing several subdirectories, or a directory tree, using the command line in Linux, generally you have to use the mkdir command several times. However, there is a faster way to do this.

Let’s say we’ve created a directory called htg, and want to create four subdirectories within it. In a normal situation, we’d use the mkdir command to create the htg directory. Then, we’d need the cd command to change to the new htg directory and, finally, we we’d use the mkdir command again four times to create the four subdirectories.

01_creating_directories_with_multiple_commands

This can all be combined into one command, and we’ll show you how.

To create a new directory with multiple subdirectories you only need to type the following command at the prompt and press Enter (obviously, change the directory names to what you want).

mkdir -p htg/{articles,images,note,done}

The -p flag tells the mkdir command to create the main directory first if it doesn’t already exist (htg, in our case). The words in the brackets are part of the “brace expansion list”. Each of the items in the brace expansion list is appended separately to the preceding path (htg/).

02_creating_directory_tree

For example, the above command is expanded into htg/articles, htg/images, htg/note, htg/done, all four of the subdirectories being created under the htg directory. As you can see in the screenshot below, it worked.

03_subdirectories_created

You can also use a brace expansion list in the mkdir command if you’re creating subdirectories in a directory that already exists, as shown below. In this example, the htg directory already exists so the subdirectories are simply added under that directory.

04_creating_subdirectories_in_an_existing_directory

You can also nest brace expansion lists in the mkdir command. For example, in the articles subdirectory under the htg directory, we want to create two subdirectories called new and rewritten. So, we type the following command at the prompt and press Enter.

mkdir -p htg/{articles/{new,rewrites},images,notes,done}

You can also use the full path if you want, as I’ve done in the example below:

mkdir -p ~/Documents/htg/{articles/{new,rewrites},images,notes,done}

The four subdirectories are created under the htg directory and then the two subdirectories, new and rewrites, are created under the articles subdirectory.

05_nesting_brace_expansion_list

RELATED: How to Make a New Directory and Change to It with a Single Command in Linux

It’s that easy. You can also combine the mkdir command with the cd command to make a directory and change to it with one command.