What a shell script is in Bash Scripting - Time & Space Complexity
We want to understand how the time a shell script takes grows as it runs commands.
How does the number of commands affect the total time?
Analyze the time complexity of the following shell script.
#!/bin/bash
for file in *.txt; do
echo "Processing $file"
wc -l "$file"
done
This script lists all text files and counts lines in each one.
Look for loops or repeated commands.
- Primary operation: The for-loop that runs commands for each text file.
- How many times: Once for each .txt file in the folder.
As the number of text files grows, the script runs more commands.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the commands inside the loop |
| 100 | About 100 times the commands inside the loop |
| 1000 | About 1000 times the commands inside the loop |
Pattern observation: The total work grows directly with the number of files.
Time Complexity: O(n)
This means the time grows in a straight line as the number of files increases.
[X] Wrong: "The script runs in the same time no matter how many files there are."
[OK] Correct: Each file adds more commands to run, so more files mean more time.
Understanding how loops affect script time helps you write efficient automation and explain your code clearly.
"What if we added a nested loop inside the for-loop? How would the time complexity change?"