Skip to main content

Colors with ANSI Escape Code

·364 words·2 mins
Posts ansi cli color console shell
Table of Contents

ANSI Escape Code
#

ANSI Escape Code is a technique used to control cussor location, color, font styling on a text terminals, aka “command line” or “cmdline” or “cli”.

In HTML world, all these can be done easily. In other environment, it may not be as simple as in HTML world.

Below are the examples, from Wikipedia, how it can be used to change the display on the terminal emulator.

ANSI Color Code
#

ForegroundBackgroundColor NameVGA
3040Black0,0,0
3141Red170,0,0
3242Green0,170,0
3343Yellow170,85,0
3444Blue0,0,170
3545Magenta170,0,170
3646Cyan0,170,170
3747White170,170,170
90100Bright Black85,85,85
91101Bright Red255,85,85
92102Bright Green85,255,85
93103Bright Yellow255,255,85
94104Bright Blue85,85,255
95105Bright Magenta255,85,255
96106Bright Cyan85,255,255
97107Bright White255,255,255

Bash (color codes)
#

Use the following template to print color text.

echo -e "\e[COLORmSample Text\e[0m"
echo -e "\e[COLOR1;COLOR2mSample Text\e[0m"
echo -e "\e[MODE;COLOR1;COLOR2mSample Text\e[0m"
OptionsDescription
echo -eInterpre blackslash escape
\e[Begin escape color change
MODEColor mode
COLOR1mColor code + ’m'
COLOR2mColor code + ’m'
\e[0mReset
ModeDescription
0Normal character
1Bold character
4Underlined character
5Blink character
7Reverse video character

Example
#

Simple test.

$ echo -e "\e[37m White_Text \e[0m"
 White_Text
$ echo -e "\e[1;34m Light_Blue_Text \e[0m"
 Light_Blue_Text
$ echo -e "\e[1;33;4;44m Underlined Yellow on Blue \e[0m"
 Underlined Tellow on Blue

Test all colors with a for-loop.

for code in {0..255}
    do echo -e "\e[38;5;${code}m"'\\e[38;5;'"$code"m"\e[0m"
done

Bash (flasher)
#

The following Bash function flashes the terminal until the user presses a key.

flasher () { while true; do printf \\e[?5h; sleep 0.1; printf \\e[?5l; read -s -n1 -t1 && break; done; }

Or, you can add it to shell script file.

#!/bin/bash

flasher () { 
  while true 
    do 
      printf \\e[?5h 
      sleep 0.1 
      printf \\e[?5l 
      read -s -n1 -t1 && break 
    done 
  }

PowerShell
#

Testing color with ANSI Escape code in PowerShell.

PS> $esc = [char]27
PS> write-host "$esc[32m Green $esc[0m"
 Green
PS> 

Links#

Related

Tunnelling with SSH Port Forwarding
·1310 words·7 mins
Posts 101 cli ssh
Quick notes on tunnelling with SSH port forwarding.
Encoding 101
·580 words·3 mins
Posts 101 cli encoding
Some notes about encoding: HTML encoding, URL encoding and ASCII encoding.
Podman 101
·1829 words·9 mins
Posts 101 podman cli tools
Docker alternative with Podman.