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
.
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}!"
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With