0
0
Bash Scriptingscripting~5 mins

File existence checks in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: File existence checks
O(n)
Understanding Time Complexity

When checking if files exist in a script, it is important to understand how the time taken grows as the number of files increases.

We want to know how the script's running time changes when we check more files.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for file in "$@"; do
  if [ -e "$file" ]; then
    echo "$file exists"
  else
    echo "$file does not exist"
  fi
done
    

This script loops through each file name given as input and checks if it exists, printing a message for each.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop that checks each file's existence one by one.
  • How many times: Once for each file passed as input.
How Execution Grows With Input

As the number of files increases, the script checks each file once, so the total work grows steadily.

Input Size (n)Approx. Operations
1010 file existence checks
100100 file existence checks
10001000 file existence checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run the script grows in a straight line as you add more files to check.

Common Mistake

[X] Wrong: "Checking one file or many files takes the same time because each check is fast."

[OK] Correct: Even if one check is quick, doing many checks adds up, so more files mean more total time.

Interview Connect

Understanding how loops over files affect time helps you write scripts that scale well and shows you can think about efficiency clearly.

Self-Check

"What if we checked files in nested directories recursively? How would the time complexity change?"