Recursive mkdir Command In Linux

The mkdir command is used to create folders or directories in the Linux operating system. By default, one-level directories or folders can be created and child folders cannot be created with a single command. But to make things easier and faster the mkdir command provides the -p option in order to create multiple parent and child directories in a single command execution even they do not exist previously.

Create Multiple Child Directories Recursively

The -p option is used to create multiple child directories with mkdir command in a recursive manner. In order to create directories recursively non of the specified directories should exist because all of them are created automatically. In the following example, we create the directories aaa , bbb and ccc . The aaa is the most upper parent of the bbb directory. The bbb is the child of the aaa and parent of the ccc.

$ mkdir -p aaa/bbb/ccc

Create Multiple Child Directories Recursively with Absolute Path

The mkdir command can be used to create directories recursively by specifying the absolute path or complete path. Providing the absolute or complete path is safer and more reliable as there is no room for error about the path. In the following example we create directories recursively in the home directory of the user ismail .

$ mkdir -p /home/ismail/aaa/bbb/ccc

Alternatively the tilda can be used to express the current user home directory.

$ mkdir -p ~/aaa/bbb/ccc

List Recusively Created Directories

The recursively created directories can be listed with the ls command in a recursive way. The -R option is used to list all child directories for the specified path. In this case we specify the parent directory “aaa” and list all child directories recusively with the following command.

$ ls -R aaa
List Recusively Created Directories

Create Multiple Child Directories with Brace Expansion

The bash provides the brace expansion which can be used to create multiple same-level children by using the recursive mkdir command. It may seem a little bit complex but very useful. The brace expansion simply specified inside the curly brackets { and } .

$ mkdir -p aaa/{1,2,3}/ccc

Lets list these multiple directories with the recursive ls command.

$ ls -R aaa
See also  Linux mkdir Command Tutorial with Examples

Leave a Comment