Appending to files (>>) in Bash Scripting - Time & Space Complexity
When we append text to a file using bash, we want to know how the time it takes changes as the file grows.
We ask: Does adding more lines make the append slower, and by how much?
Analyze the time complexity of the following code snippet.
for ((i=1; i<=n; i++)); do
echo "Line $i" >> output.txt
done
This script appends n lines to a file named output.txt, one line at a time.
- Primary operation: Appending one line to the file using
>>inside a loop. - How many times: Exactly n times, once per loop iteration.
Each append adds one line, and the loop runs n times, so the total work grows as we add more lines.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 appends |
| 100 | 100 appends |
| 1000 | 1000 appends |
Pattern observation: The time grows directly with the number of lines added.
Time Complexity: O(n)
This means the time to append grows in a straight line as you add more lines.
[X] Wrong: "Appending to a file is instant no matter how big the file is."
[OK] Correct: Each append operation takes some time, so doing many appends adds up and takes longer as n grows.
Understanding how loops and file operations scale helps you explain script efficiency clearly and confidently.
What if we collected all lines in a variable and wrote them to the file once? How would the time complexity change?