Create Directories Recursively With mkdir
Razvan Ludosanu
Founder, learnbackend.dev
Published: 5/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:
$ mkdir -p <path>
Where:
- path is a path containing a list of nested directories separated by a slash character.
For example:
$ 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:
$ mkdir -v -p <path>
For example:
$ 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:
$ mkdir -p <path> …
For example:
$ 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.
$ 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:
$ 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:
$ 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:
$ 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:
#!/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:
$ ./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:
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:
import os
os.makedirs("app/tmp/logs", exist_ok = True)
Written by
Razvan Ludosanu
Founder, learnbackend.dev
Filed Under
Related Articles
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.
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.
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.
Linux Chmod Command
Understand how to use chmod to change the permissions of files and directories. See examples with various chmod options.
POST JSON Data With Curl
How to send valid HTTP POST requests with JSON data payloads using the curl command and how to avoid common syntax pitfalls. Also, how to solve the HTTP 405 error code.
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.
Create Groups In Linux
Learn how to manually and automatically create and list groups in Linux.
Switch Users In Linux
Learn how to switch between users, log in as another user, and execute commands as another user in Linux.
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.
Delete Files In Linux
Learn how to selectively delete files in Linux based on patterns and properties using the rm command.
Find Files In Linux
Learn how to find and filter files in Linux by owner, size, date, type and content using the find command.
Copy Files In Linux
Learn how to safely and recursively copy one or more files locally and remotely in Linux using the cp and scp command.