Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 695
Adrian E Avatar asked May 09 '16 11:05

Adrian E


People also ask

How do I change the output color in bash?

For example, if you wanted to print green text, you could do the following: #!/bin/bash # Set the color variable green='\033[0;32m' # Clear the color after that clear='\033[0m' printf "The script was executed ${green}successfully${clear}!"

How do you change the color of the text in Shell?

Colors for text are represented by color codes, including, reset = 0, black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, and white = 37. Here, \e[1;31m is the escape string to set the color to red and \e[0m resets the color back. Replace 31 with the required color code.

How do I change the color of my output in terminal?

Fortunately, there's another option: the tput command. It enables us to query the terminfo database and provides a convenient way to extract escape codes we need. “tput setaf” sets foreground color, “tput setab” sets background color, and “tput sgr0” resets all the settings to terminal default.


1 Answers

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.

like image 118
chepner Avatar answered Sep 20 '22 20:09

chepner