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?

1 Answer 1

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' 
2
  • Perfect, thanks a lot, it's crystal clear now! ANSI sequences are introduced by the special Esc value, which is not printable, hence the -e option which eases its usage using ascii \e. Commented May 3, 2019 at 12:48
  • 2
    Do not forget foo=$'\e[32mFOO\e[0m'. Commented May 3, 2019 at 13:12

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.