0
0
Bash Scriptingscripting~5 mins

Color output (ANSI escape codes) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Color output (ANSI escape codes)
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of lines to print increases, the script runs more print commands, each with color codes.

Input Size (n)Approx. Operations
1010 print commands with color codes
100100 print commands with color codes
10001000 print commands with color codes

Pattern observation: The number of operations grows directly with the number of lines printed.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the script grows linearly with the number of lines printed, even with color codes.

Common Mistake

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

Interview Connect

Understanding how adding features like color output affects script performance helps you write efficient scripts and explain your reasoning clearly in interviews.

Self-Check

"What if we added nested loops to print a colored grid of text? How would the time complexity change?"