Bash – Store Color Codes in Variable

bashcolorsvariable

How do I store colored text in a variable and print it with color later?

I never see the answer to this question in 100 searches it's all about PS1 prompts, or inline printf's or using data from ls –color. I need to add the color to the variable myself AND have it print colorized later.

name="Hello"
name=$name"\e[36m\(Test\)\e[0m"
echo $name
printf $name

the ouptut i get from this is:

Hello \e[36m(Test)\e0m

It doesn't colorize from the data in the variable.
how do we STORE the color code in a variable for printing later
Thanks
Jaeden "Sifo Dyas" al'Raec Ruiner

Best Answer

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
Related Question