Monday, February 3, 2025

ANSI escape sequences to print colored text(linux terminal)


ANSI escape sequences are a standardized way to add color and formatting to text in the terminal. Here are some common ANSI escape sequences for printing colored text:

Color Codes(Foreground)

Color

Code

Reset

\033[0m

Black

\033[30m

Red

\033[31m

Green

\033[32m

Yellow

\033[33m

Blue

\033[34m

Magenta

\033[35m

Cyan

\033[36m

White

\033[37m

Background Color Codes

Color

Code

Black Background

\033[40m

Red Background

\033[41m

Green Background

\033[42m

Yellow Background

\033[43m

Blue Background

\033[44m

Magenta Background

\033[45m

Cyan Background

\033[46m

White Background

\033[47m



Example Usage in Python

print("\033[31m" + "This text is red" + "\033[0m")

print("\033[32m" + "This text is green" + "\033[0m")

print("\033[34m" + "This text is blue" + "\033[0m")

print("\033[41m" + "This text has a red background" + "\033[0m")

print("\033[42m" + "This text has a green background" + "\033[0m")

Note

  • ANSI escape sequences may not work on all systems or terminals.
  • The \033[ code is the ESCAPE sequence that starts the ANSI command.
  • The m at the end of each code is what actually applies the change.

Other useful escape sequences:

To clear the whole line in a bash script when using \r to print on the same line, you can use the following methods:

Method 1: Using ANSI Escape Sequences

Bash

echo -ne "\r\033[K"

  • \r moves the cursor to the beginning of the line.
  • \033[K clears the line from the cursor position to the end.
Using printf command:

printf "\r%s \x1b[32m%s\x1b[0m\033[K\n" "$test_name" "Passed."

Method 2: Using tput

Bash

echo -ne "\r$(tput el)"

  • \r moves the cursor to the beginning of the line.
  • tput el clears the line from the cursor position to the end.

Example Usage

Bash

for i in {1..10}; do
    echo -ne "\rProgress: $i%"
    sleep 0.5
done
echo -ne "\r\033[K"
echo "Done!"

In this example, the progress is printed on the same line, and after the loop finishes, the line is cleared, and "Done!" is printed.

 

 

No comments: