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:
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:
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:
The other way is to store the codes inside a variable, and interpret them each time their "effect" is needed.
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:The whole list of colors (background) will be visible with (printing an space):
Or, with foreground colors: