How to Create Nested Directory in Linux Quickly
Use the
mkdir -p command followed by the nested directory path to create all required directories at once. For example, mkdir -p folder1/folder2/folder3 creates all three folders in one step.Syntax
The basic syntax to create nested directories is:
mkdir: The command to make directories.-p: Option to create parent directories as needed without errors.path/to/directory: The nested directory path you want to create.
bash
mkdir -p path/to/nested/directory
Example
This example creates a nested directory structure projects/python/scripts in one command. It creates all missing parent folders automatically.
bash
mkdir -p projects/python/scripts ls -R projects
Output
projects:
python
projects/python:
scripts
projects/python/scripts:
Common Pitfalls
Without the -p option, mkdir will fail if any parent directory does not exist. For example, mkdir projects/python/scripts fails if projects/python is missing.
Also, avoid trailing slashes that might confuse some shells, though usually they are fine.
bash
mkdir projects/python/scripts # This will fail if 'projects/python' does not exist mkdir -p projects/python/scripts # This works even if parents are missing
Output
mkdir: cannot create directory ‘projects/python/scripts’: No such file or directory
Quick Reference
Remember these tips when creating nested directories:
- Use
-pto create all needed parent folders. - Check permissions if creation fails.
- Use relative or absolute paths as needed.
- Use
ls -Rto verify nested folders.
Key Takeaways
Use
mkdir -p to create nested directories in one command.Without
-p, mkdir fails if parent folders don't exist.Check folder permissions if directory creation fails.
Use relative or absolute paths depending on your location.
Verify created folders with
ls -R.