In bash there are three options: echo -e
, printf
, and $'...'
.
The last one is the easiest:
$ name="Hello"; name=$name$'\033[34m(Test)\e[0m' ; echo "$name"
Hello(Test)
In this case the color code was stored in the variable. The easiest way to "see" the codes (apart from seeing the color) is to use some hex viewer:
$ echo "$name" | od -vAn -tcx1
H e l l o 033 [ 3 5 m ( T e s t )
48 65 6c 6c 6f 1b 5b 33 35 6d 28 54 65 73 74 29
033 [ 0 m \n
1b 5b 30 6d 0a
Use it when you need to "see" the codes (and why they do or don't work).
The color codes are inside the var, already interpreted. In that way you could create a var for some color, and use it:
$ blue=$'\033[34m'; reset=$'\033[0m'
$ echo "Hello $blue Test $reset Colors"
The other way is to store the codes inside a variable, and interpret them each time their "effect" is needed.
$ blue='\033[34m'; reset='\033[0m'
$ echo "Hello $blue Test $reset Colors"
Hello \033[34m Test \033[0m Colors
$ echo -e "Hello $blue Test $reset Colors"
Hello Test Colors
With "Test" in Blue, and "Colors" in Black (if your console screen is white).
The command echo -e
is not as portable (and safe) as printf:
$ blue='\033[34m'; reset='\033[0m'
$ printf "%s $blue%s $reset%s" "Hello" "Test" "Colors"
Hello Test Colors
The whole list of colors (background) will be visible with (printing an space):
printf '\e[%sm ' {40..47} 0; echo
Or, with foreground colors:
printf '\e[%smColor=%s ' {30..37}{,} 0 0; echo
Best Answer
The count of colors available to tput is given by
tput colors
.To see the basic 8 colors (as used by
setf
in urxvt terminal andsetaf
in xterm terminal):And usually named as this:
To see the extended 256 colors (as used by
setaf
in urxvt):If you want numbers and an ordered output:
The 16 million colors need quite a bit of code (some consoles can not show this).
The basics is:
fb
isfront/back
or3/4
.A simple test of your console capacity to present so many colors is:
It will present a red line with a very small change in tone from left to right. If that small change is visible, your console is capable of 16 million colors.
Each
r
,g
, andb
is a value from 0 to 255 for RGB (Red,Green,Blue).If your console type support this, this code will create a color table:
To convert an hex color value to a (nearest) 0-255 color index:
Use it as:
To find the color number as used in HTML colors format:
Use it as ("basic" is the first 16 colors, "color" is the main group, "gray" is the last gray colors):