test command and [ ] syntax in Bash Scripting - Time & Space Complexity
We want to understand how the time taken by bash test commands grows as we check more conditions.
How does the number of checks affect the total time?
Analyze the time complexity of the following bash snippet using test or [ ] syntax.
for file in *; do
if [ -f "$file" ]; then
echo "$file is a regular file"
fi
done
This code loops over all items in the current folder and tests if each is a regular file.
Look for repeated actions in the code.
- Primary operation: The test command [ -f "$file" ] runs once per file.
- How many times: It runs once for each item in the folder, so as many times as there are files.
As the number of files grows, the number of test commands grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 test commands |
| 100 | 100 test commands |
| 1000 | 1000 test commands |
Pattern observation: The number of tests 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 test command runs only once regardless of files."
[OK] Correct: The test runs inside the loop, so it runs once per file, not just once total.
Understanding how loops and tests scale helps you write efficient scripts and answer questions about script speed.
"What if we added a nested loop inside that also runs tests? How would the time complexity change?"