Logical operators (-a, -o, !) in Bash Scripting - Time & Space Complexity
We want to see how the time it takes to run a bash script with logical operators changes as input conditions grow.
How does combining conditions with -a, -o, and ! affect the script's speed?
Analyze the time complexity of the following code snippet.
count=0
while [ $count -lt $n ]; do
if [ -f "file$count.txt" -a ! -s "file$count.txt" ]; then
echo "Empty file: file$count.txt"
fi
count=$((count + 1))
done
This script checks files named file0.txt to file(n-1).txt to see if they exist and are empty.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs the test on each file.
- How many times: It runs once for each file from 0 to n-1, so n times.
Each new file adds one more check with two conditions combined by logical operators.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks of two conditions each |
| 100 | About 100 checks of two conditions each |
| 1000 | About 1000 checks of two conditions each |
Pattern observation: The total checks grow directly with the number of files.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of files increases.
[X] Wrong: "Using -a and -o makes the script run much slower because it checks many conditions inside each loop."
[OK] Correct: Each condition check is simple and happens once per loop. The total time still grows linearly with the number of files, not exponentially.
Understanding how logical operators affect script speed helps you write efficient checks in real scripts, a useful skill in many automation tasks.
"What if we replaced the while loop with nested loops checking pairs of files? How would the time complexity change?"