0
0
Bash Scriptingscripting~5 mins

Logical operators (-a, -o, !) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Logical operators (-a, -o, !)
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each new file adds one more check with two conditions combined by logical operators.

Input Size (n)Approx. Operations
10About 10 checks of two conditions each
100About 100 checks of two conditions each
1000About 1000 checks of two conditions each

Pattern observation: The total checks grow directly with the number of files.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the number of files increases.

Common Mistake

[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.

Interview Connect

Understanding how logical operators affect script speed helps you write efficient checks in real scripts, a useful skill in many automation tasks.

Self-Check

"What if we replaced the while loop with nested loops checking pairs of files? How would the time complexity change?"