Jonah
Jonah

Reputation: 16202

Terminal color codes not working in bash on my mac

According to this page, the following should output colorized characters:

$ B=(' ' '\E[0;31m.' '\E[0;31m:' '\E[1;31m+' '\E[0;33m+' '\E[1;33mU' '\E[1;33mW');
$ echo -e ${B[*]}

Instead, for me on Mac OS X (GNU bash, 4.4.0), it just echoes back literally:

\E[0;31m. \E[0;31m: \E[1;31m+ \E[0;33m+ \E[1;33mU \E[1;33mW

Do I need to enable / disable some setting to make this work?

Upvotes: 1

Views: 2961

Answers (2)

pynexj
pynexj

Reputation: 20688

Not sure what's the real problem but you can use Bash's $'...' syntax for the ESC char:

[STEP 101] $ B=($'\e[0;31m.' $'\e[0;31m:' $'\e[1;31m+' $'\e[0;33m+' $'\e[1;33mU' $'\e[1;33mW')
[STEP 102] $ echo ${B[@]}
. : + + U W

enter image description here

Another option is use printf which is more consistent:

[STEP 104] $ printf '\e[1;31mhello\e[0m\n'
hello

enter image description here

Upvotes: 3

jwodder
jwodder

Reputation: 57470

For licensing reasons, the version of Bash installed by default on macOS is version 3, even though version 4 has been around since 2009. The \E escape sequence was apparently introduced in version 4 or one of its minor versions, and thus it does not work in version 3. However, \E is apparently just a synonym for \e, which does work in v3, and so changing \E to \e in your code snippet should allow it to work.

Upvotes: 1

Related Questions