0
0
Bash Scriptingscripting~5 mins

read command in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: read command
O(n)
Understanding Time Complexity

We want to understand how the time taken by the read command changes as the input size grows.

Specifically, how does reading input line by line affect the total time?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

#!/bin/bash

while read line; do
  echo "$line"
done < input.txt

This script reads each line from a file and prints it out one by one.

Identify Repeating Operations
  • Primary operation: Reading and printing each line inside the while read loop.
  • How many times: Once for every line in the input file.
How Execution Grows With Input

Each line causes one read and one print operation, so the total work grows directly with the number of lines.

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

Pattern observation: The total time grows in a straight line as the number of lines increases.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly in proportion to the number of lines read.

Common Mistake

[X] Wrong: "The read command always takes constant time no matter how many lines there are."

[OK] Correct: Each line requires a separate read operation, so more lines mean more time.

Interview Connect

Understanding how input reading scales helps you write scripts that handle large files efficiently and shows you can think about performance in real tasks.

Self-Check

"What if we read the entire file at once into a variable instead of line by line? How would the time complexity change?"