Bash Script to Create Directory Structure Easily
mkdir -p path/to/directory inside a script to create a directory structure, including any necessary parent directories.Examples
How to Think About It
mkdir command can create one directory or many nested directories. Using the -p option tells Bash to create all parent directories if they don't exist, so you don't have to create each level one by one.Algorithm
Code
#!/bin/bash # Directory path to create DIR_PATH="projects/2024/april" # Create directory structure mkdir -p "$DIR_PATH" # Confirm creation if [ -d "$DIR_PATH" ]; then echo "Directory structure '$DIR_PATH' created successfully." else echo "Failed to create directory structure." fi
Dry Run
Let's trace creating 'projects/2024/april' through the script
Set directory path
DIR_PATH="projects/2024/april"
Run mkdir with -p
mkdir -p "projects/2024/april" creates all missing directories
Check if directory exists
[ -d "projects/2024/april" ] returns true if directory exists
| Step | Action | Value |
|---|---|---|
| 1 | Set DIR_PATH | projects/2024/april |
| 2 | Create directories | mkdir -p projects/2024/april |
| 3 | Check directory | Directory exists: true |
Why This Works
Step 1: Using mkdir -p
The -p option tells mkdir to create parent directories as needed, so the full path is created in one command.
Step 2: Checking directory existence
The test [ -d "$DIR_PATH" ] checks if the directory now exists to confirm success.
Step 3: Printing confirmation
A message is printed to inform the user whether the directory structure was created successfully.
Alternative Approaches
#!/bin/bash DIRS=(projects 2024 april) CURRENT="" for d in "${DIRS[@]}"; do CURRENT="$CURRENT/$d" mkdir "$CURRENT" done echo "Directories created step by step."
#!/bin/bash
mkdir myfolder
echo "Single directory created."Complexity: O(n) time, O(1) space
Time Complexity
The time depends on the number of directories to create (n). mkdir -p creates each missing directory once, so it's linear in the depth of the path.
Space Complexity
The script uses constant extra space, only storing the directory path string and temporary variables.
Which Approach is Fastest?
Using mkdir -p is fastest and simplest compared to looping through each directory level manually.
| Approach | Time | Space | Best For |
|---|---|---|---|
| mkdir -p | O(n) | O(1) | Creating nested directories efficiently |
| Loop creating each directory | O(n) | O(1) | Manual control but more code |
| mkdir without -p | O(1) | O(1) | Single directory, parents must exist |
mkdir -p to safely create nested directories without errors if parents are missing.-p option causes errors if parent directories don't exist.