Running scripts in Bash Scripting - Time & Space Complexity
When we run a script, we want to know how long it takes as the work grows.
We ask: How does running time change when the script handles more data or commands?
Analyze the time complexity of the following code snippet.
#!/bin/bash
for file in /path/to/folder/*; do
echo "Processing $file"
grep "pattern" "$file"
done
This script lists files in a folder and searches each file for a pattern.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each file in the folder.
- How many times: Once for each file found in the folder.
As the number of files grows, the script runs the loop more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times running grep |
| 100 | 100 times running grep |
| 1000 | 1000 times running grep |
Pattern observation: The work grows directly with the number of files.
Time Complexity: O(n)
This means the running time grows in a straight line as the number of files increases.
[X] Wrong: "Running the script takes the same time no matter how many files there are."
[OK] Correct: Each file adds more work because the script processes them one by one.
Understanding how script running time grows helps you explain your code's efficiency clearly and confidently.
"What if we changed the script to process files in parallel? How would the time complexity change?"