0

I really struggle understanding the behavior of echo (and others such commands) while processing ANSI escape codes to print colored messages.

I know I can use the -e option like this:

echo -e "\e[32m FOO \e[0m"

My message will be successfully colored.

Also, I noticed that I could assign the output of echo -e to a variable, and then re-use this variable in a new echo command without the -e option, and this would work anyway.

foo=$(echo -e "\e[32m FOO \e[0m")
echo $foo

So, what are the actual "raw bytes" emitted by echo -e when encountering ANSI codes? What does my foo variable contain? How could I integrate them directly in my echo "??? FOO ???" without needing the -e option?

Delgan
  • 161

1 Answers1

3

The "raw output" of your initial echo will contain actual Escape characters (ASCII code 27, octal 033) instead of \e. The rest of the string remains as is. It's the -e option to echo in bash that replaces the \e character sequences with the Escape characters (just like it would replace \t by a tab etc.)

To incorporate an Escape character directly into $foo without going through echo -e, you would have to type an actual literal Escape character into the string.

In bash, you can type a literal Escape character by pressing Ctrl+V followed by Esc.

In a terminal, this would look like

foo="^[[32mFOO^[[0m"

where each ^[ is generated by Ctrl+V followed by Esc.

Or, you could use $'...' ("C string interpolation" in bash) to expand \e:

foo=$'\e[32mFOO\e[0m'
Kusalananda
  • 333,661