0
0
Bash Scriptingscripting~5 mins

Writing to files (echo, printf) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing to files (echo, printf)
O(n)
Understanding Time Complexity

When writing data to files using bash commands like echo or printf, it is important to understand how the time taken grows as the amount of data increases.

We want to know how the execution time changes when writing more lines or bigger content to a file.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

for i in $(seq 1 $n); do
  echo "Line $i" >> output.txt
  printf "Number: %d\n" "$i" >> output.txt
done

This script writes two lines to a file for each number from 1 to n.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop runs n times.
  • How many times: Each iteration writes two lines to the file using echo and printf.
How Execution Grows With Input

As n increases, the number of write operations grows directly with it.

Input Size (n)Approx. Operations
1020 writes
100200 writes
10002000 writes

Pattern observation: The total writes increase linearly as n grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to write grows in direct proportion to the number of lines you want to write.

Common Mistake

[X] Wrong: "Writing multiple lines inside a loop is constant time because each write is fast."

[OK] Correct: Each write takes time, so more lines mean more total time. The time adds up linearly, not stays the same.

Interview Connect

Understanding how writing to files scales helps you reason about script performance and resource use in real tasks.

Self-Check

"What if we buffered all lines in a variable and wrote once at the end? How would the time complexity change?"