0
0
Bash Scriptingscripting~5 mins

What a shell script is in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: What a shell script is
O(n)
Understanding Time Complexity

We want to understand how the time a shell script takes grows as it runs commands.

How does the number of commands affect the total time?

Scenario Under Consideration

Analyze the time complexity of the following shell script.

#!/bin/bash

for file in *.txt; do
  echo "Processing $file"
  wc -l "$file"
done

This script lists all text files and counts lines in each one.

Identify Repeating Operations

Look for loops or repeated commands.

  • Primary operation: The for-loop that runs commands for each text file.
  • How many times: Once for each .txt file in the folder.
How Execution Grows With Input

As the number of text files grows, the script runs more commands.

Input Size (n)Approx. Operations
10About 10 times the commands inside the loop
100About 100 times the commands inside the loop
1000About 1000 times the commands inside the loop

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

[OK] Correct: Each file adds more commands to run, so more files mean more time.

Interview Connect

Understanding how loops affect script time helps you write efficient automation and explain your code clearly.

Self-Check

"What if we added a nested loop inside the for-loop? How would the time complexity change?"