First Bash script in Bash Scripting - Time & Space Complexity
When we write a bash script, it is important to know how the time it takes to run changes as we give it more work.
We want to understand how the script's running time grows when the input size grows.
Analyze the time complexity of the following code snippet.
#!/bin/bash
for file in /path/to/directory/*; do
echo "Processing $file"
done
This script lists all files in a directory and prints a message for each file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each file name.
- How many times: Once for every file in the directory.
As the number of files increases, the script runs the loop more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the echo command runs |
| 100 | About 100 times the echo command runs |
| 1000 | About 1000 times the echo command runs |
Pattern observation: The work grows directly with the number of files.
Time Complexity: O(n)
This means the script takes longer roughly in direct proportion to how many files it processes.
[X] Wrong: "The script runs in the same time no matter how many files there are."
[OK] Correct: Each file adds one more loop step, so more files mean more work and more time.
Understanding how loops affect running time is a key skill. It helps you write scripts that handle bigger tasks smoothly.
"What if we changed the script to process files in subdirectories too? How would the time complexity change?"