Search code examples
bashterminalitermansi-escape

Bash printing color codes literally and not in actual color


For some reason my shell script stopped printing my menu in color and is actually printing the literal color code instead. Did I somehow escape the color coding?

Script

#!/bin/bash 

function showEnvironments {
echo -e "\e[38;5;81m"
echo -e "      SELECT ENVIRONMENT       "
echo -e "[1] - QA"
echo -e "[2] - PROD"
echo -e "\e[0m"
}

showEnvironments

Output

\e[38;5;81m

SELECT ENVIRONMENT

[1] - Staging

[2] - QA

\e[0m

I am using iTerm on Mac OSX and the TERM environment variable is set to xterm-256color.


Solution

  • There are several apparent bugs in the implementation of echo -e in bash 3.2.x, which is what ships with Mac OS X. The documentation claims that \E (not \e) represents ESC, but neither appears to work. You can use printf instead:

    printf "\e[38;5;81mfoo\e[0m\n"
    

    or use (as you discovered) \033 to represent ESC.

    Later versions of bash (definitely 4.3, possible earlier 4.x releases as well) fix this and allow either \e or \E to be used.