mkdir (create directories) in Linux CLI - Time & Space Complexity
When creating directories using the mkdir command, it's helpful to understand how the time it takes grows as you create more directories.
We want to know how the work done by mkdir changes when the number of directories increases.
Analyze the time complexity of the following code snippet.
for dir in dir1 dir2 dir3 dir4 dir5; do
mkdir "$dir"
done
This script creates five directories one by one using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
mkdircommand inside the loop creates one directory per iteration. - How many times: The loop runs once for each directory name, so it runs n times if there are n directories.
Each directory creation takes roughly the same amount of time, so total time grows as you add more directories.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 mkdir commands run |
| 100 | 100 mkdir commands run |
| 1000 | 1000 mkdir commands run |
Pattern observation: The total work grows directly with the number of directories you create.
Time Complexity: O(n)
This means the time to create directories grows linearly with how many directories you want to make.
[X] Wrong: "Creating multiple directories with mkdir is always instant no matter how many directories."
[OK] Correct: Each directory creation takes some time, so more directories mean more total time, even if each one is quick.
Understanding how simple commands like mkdir scale helps you think clearly about scripts and automation tasks in real work.
"What if we used mkdir -p to create nested directories in one command? How would the time complexity change?"