0
0
Bash Scriptingscripting~5 mins

Looping over files and directories in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Looping over files and directories
O(n)
Understanding Time Complexity

When we loop over files and directories in a script, we want to know how the time it takes grows as the number of files grows.

We ask: How does the script's work increase when there are more files?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

for file in /path/to/directory/*; do
  if [ -f "$file" ]; then
    echo "Processing $file"
  fi
done

This script loops over each item in a directory and prints a message for each file found.

Identify Repeating Operations
  • Primary operation: Looping over each file and checking if it is a regular file.
  • How many times: Once for every item in the directory.
How Execution Grows With Input

As the number of files increases, the script does more checks and prints more messages.

Input Size (n)Approx. Operations
10About 10 checks and prints
100About 100 checks and prints
1000About 1000 checks and prints

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The script runs in the same time no matter how many files there are."

[OK] Correct: Each file adds more work because the loop runs once per file, so more files mean more time.

Interview Connect

Understanding how loops over files scale helps you write scripts that handle many files efficiently and shows you can think about script performance clearly.

Self-Check

"What if we added a nested loop inside to process each file's lines? How would the time complexity change?"