Create Directories Recursively With mkdir

Razvan Ludosanu
Razvan LudosanuFounder, learnbackend.dev
Published: May 20, 2024

The short answer

On Unix-like operating systems such as Linux and macOS, you can recursively create multiple nested directories at once using the mkdir  command with the -p  flag as follows:

Bash
$ mkdir -p <path>

Where:

  • path  is a path containing a list of nested directories separated by a slash character.

For example:

Bash
$ mkdir -p app/tmp/logs

This command will first create the app  directory within the local directory, then create the tmp  directory within the app  directory, and finally create the logs  directory within the tmp  directory.

Note that if an intermediate directory already exists, no error will be reported, and the mkdir  command will simply continue its operation.

Easily retrieve this command using Warp’s AI Command Suggestions

If you’re using Warp as your terminal, you can easily retrieve this command using the Warp AI Command Suggestions feature:

Entering mkdir recursive  in the AI Command Suggestions will prompt a mkdir  command that can then quickly be inserted into your shell by doing CMD+ENTER .

Enabling verbose output

Since, by default, the mkdir  command silently skips existing directories, you can enable the verbose mode using the -v  flag, which will output the list of directories as they are created:

Bash
$ mkdir -v -p <path>

For example:

Bash
$ mkdir -p app/tmp/logs
app/tmp/logs

The output of this command indicates that only the logs  directory was created as the app  and tmp  directories already exist.

Creating multiple directories in a parent directory

To recursively create multiple directories at once within the same parent directory, you can use the following syntax:

Bash
$ mkdir -p <path> …

For example:

Bash
$ mkdir -p src/public src/utils tmp/logs

This command will create the src  and tmp  directories within the same parent directory, including their intermediate directories public , utils , and logs .

Common errors and pitfalls

When creating directories using the mkdir  command, there are several common errors and pitfalls that you should be aware of in order to avoid running into issues.

Insufficient file permissions

One of the most common errors is when attempting to create a directory within a directory you don't have write and execute permissions on.

Bash
$ mkdir -p app/tmp
mkdir: app/tmp: Permission denied

To check the permissions of a directory, you can use the ls -l  command within its parent directory as follows:

Bash
$ ls -l
drwxr-xr-x  3 john  staff     96 Oct 24 17:07 app

Which will output the permissions for the owner, the group, and the other users.

You can learn more about permissions with our articles on Unix file permissions and how to use the chmod command.

Conflict with existing files

Another common error is when attempting to create a directory within a directory that already contains an entry with the same name.

For example, if the target directory contains a directory with the same, the mkdir command will throw a "File exists" error:

Bash
$ mkdir -p app
mkdir: app: File exists

On the other hand, if the target directory contains a regular file with the same name, the mkdir  command will throw a "Not a directory" error:

Bash
$ mkdir -p app/tmp
mkdir: app: Not a directory

Syntax errors

Finally, you should avoid using special characters, spaces, or non-standard characters in the directory path as it could lead to unexpected results. For example, the following characters have a special meaning for the shell and should be avoided: < , > , | , \ , : , ( , ) , & . For that it is recommended to only use lowercase and uppercase characters, numbers, dots, and replace spaces with underscores ( \_ ) and hyphens ( - ).

Recursively creating directories using scripts

For large scale or collaborative projects, scripts are often used to create complex and nested directory structures in order to save time and ensure consistency and reproducibility on different environments, thus mitigating the risk of human error.

In short, scripts allow developers to easily set up projects by automating the creation of their initial directory structure, dynamically creating directories depending on conditions or variables, or creating directories in bulk using loops and patterns.

Using a Bash script

To create nested directories in Bash, you can use a for  loop that iterates on the elements of an array of paths and executes the mkdir  command for each of these paths as follows:

Bash
#!/bin/bash

directories=("app/src" "app/tmp/logs")

for directory in "${directories[@]}";
do
  mkdir -v -p $directory
done

When executed, this script will generate the following output:

Bash
$ ./script.sh
app
app/src
app/tmp
app/tmp/logs

Using a Python script

To create nested directories in Python, you can use the makedirs  method of the os  package as follows:

Bash
import os

os.makedirs("app/tmp/logs")

Note that if any of these directories already exists, the makedirs  method will throw an error.

This can be avoided by using the "exist\_ok" parameter as follows:

Bash
import os

os.makedirs("app/tmp/logs", exist_ok = True)
Written by
Razvan Ludosanu
Razvan LudosanuFounder, learnbackend.dev
Filed under

Related articles


Bash Comments

Comments will help make your scripts more readable

Reading User Input

Via command line arguments and prompting users for input

Curl Post Request

Use cURL to send data to a server

Upload Files With curl

Learn how to upload a file to FTP, SFTP servers, Artifactory, and AWS S3 using the curl command.

How To Copy A Directory In Linux

Learn how to copy directories and their content in Linux using the cp command with options like -r for recursive copying, -i for interactive mode, and -a for preserving attributes.

Create Groups In Linux

Learn how to manually and automatically create and list groups in Linux.

How to Check the Size of Folders in Linux

Learn how to output the size of directories and subdirectories in a human-readable format in Linux and macOS using the du command.

Count Files in Linux

Learn how to count files and folders contained in directories and subdirectories in Linux using the ls, find, and wc commands.

List Open Ports in Linux

Learn how to output the list of open TCP and UDP ports in Linux, as well as their IP addresses and ports using the netstat command.

Format Command Output In Linux

Learn how to filter and format the content of files and the output of commands in Linux using the awk command.

Remover Users in Linux

Learn how to remove local and remote user accounts and associated groups and files in Linux using the userdel and deluser commands.

Switch Users In Linux

Learn how to switch between users, log in as another user, and execute commands as another user in Linux.