0
0
Bash Scriptingscripting~5 mins

Appending to files (>>) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Appending to files (>>)
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Appending one line to the file using >> inside a loop.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

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
1010 appends
100100 appends
10001000 appends

Pattern observation: The time grows directly with the number of lines added.

Final Time Complexity

Time Complexity: O(n)

This means the time to append grows in a straight line as you add more lines.

Common Mistake

[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.

Interview Connect

Understanding how loops and file operations scale helps you explain script efficiency clearly and confidently.

Self-Check

What if we collected all lines in a variable and wrote them to the file once? How would the time complexity change?