0
0
Bash Scriptingscripting~5 mins

[[ ]] extended test in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: [[ ]] extended test
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

As the number of files increases, the script checks each file once with two conditions.

Input Size (n)Approx. Operations
10About 20 condition checks (2 per file)
100About 200 condition checks
1000About 2000 condition checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the number of files checked.

Common Mistake

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

Interview Connect

Understanding how loops and condition checks scale helps you write efficient scripts and explain your reasoning clearly in interviews.

Self-Check

What if we added a nested loop inside the for-loop that also checks each file? How would the time complexity change?