Writing to files (echo, printf) in Bash Scripting - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop runsntimes. - How many times: Each iteration writes two lines to the file using
echoandprintf.
As n increases, the number of write operations grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 writes |
| 100 | 200 writes |
| 1000 | 2000 writes |
Pattern observation: The total writes increase linearly as n grows.
Time Complexity: O(n)
This means the time to write grows in direct proportion to the number of lines you want to write.
[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.
Understanding how writing to files scales helps you reason about script performance and resource use in real tasks.
"What if we buffered all lines in a variable and wrote once at the end? How would the time complexity change?"