Color output (ANSI escape codes) in Bash Scripting - Time & Space Complexity
We want to understand how the time it takes to run a script changes when we add color output using ANSI escape codes.
Specifically, does adding color affect how long the script runs as the output grows?
Analyze the time complexity of the following code snippet.
#!/bin/bash
for i in {1..100}
do
echo -e "\033[31mLine $i\033[0m"
done
This script prints 100 lines, each line colored red using ANSI escape codes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each line with color codes.
- How many times: 100 times, once per line.
As the number of lines to print increases, the script runs more print commands, each with color codes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print commands with color codes |
| 100 | 100 print commands with color codes |
| 1000 | 1000 print commands with color codes |
Pattern observation: The number of operations grows directly with the number of lines printed.
Time Complexity: O(n)
This means the time to run the script grows linearly with the number of lines printed, even with color codes.
[X] Wrong: "Adding color codes makes the script run much slower and changes the time complexity."
[OK] Correct: The color codes are just extra characters printed each time, so they add a small constant cost per line but do not change how the total time grows with more lines.
Understanding how adding features like color output affects script performance helps you write efficient scripts and explain your reasoning clearly in interviews.
"What if we added nested loops to print a colored grid of text? How would the time complexity change?"