[[ ]] extended test in Bash Scripting - Time & Space Complexity
We want to understand how the time it takes to run a bash script using the [[ ]] extended test changes as the input grows.
Specifically, we ask: how does the number of checks scale when testing multiple conditions?
Analyze the time complexity of the following code snippet.
#!/bin/bash
for file in *; do
if [[ -f "$file" && -r "$file" ]]; then
echo "$file is a readable file"
fi
done
This script loops over all items in the current folder and checks if each is a regular file and readable.
- Primary operation: The for-loop iterates over each file in the directory.
- How many times: Once for each file found (n times).
- Inside the loop: The [[ ]] test checks two conditions per file.
As the number of files increases, the script checks each file once with two conditions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 condition checks (2 per file) |
| 100 | About 200 condition checks |
| 1000 | About 2000 condition checks |
Pattern observation: The total checks grow linearly with the number of files.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the number of files checked.
[X] Wrong: "The [[ ]] test runs in constant time no matter how many files there are."
[OK] Correct: Each file requires its own check, so the total time grows with the number of files.
Understanding how loops and condition checks scale helps you write efficient scripts and explain your reasoning clearly in interviews.
What if we added a nested loop inside the for-loop that also checks each file? How would the time complexity change?