问题
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
.
回答1:
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.
回答2:
Two ways to do this: reference colors directly or assign to variable to reference them easier later in the script.
cNone='\033[00m'
cRed='\033[01;31m'
cGreen='\033[01;32m'
cYellow='\033[01;33m'
cPurple='\033[01;35m'
cCyan='\033[01;36m'
cWhite='\033[01;37m'
cBold='\033[1m'
cUnderline='\033[4m'
echo -e "\033[01;31m"
echo -e "hello"
echo -e "\033[00m"
echo -e "${cGreen}"
echo -e "hello"
echo -e "${cNone}"
I hope this helps.
回答3:
I figured it out. It appears that the escape character I am using for the color code is not recognized in my terminal.
Based on http://misc.flogisoft.com/bash/tip_colors_and_formatting#colors1 valid escape codes are:
\e
\033
\x1B
When I changed my colors from \e[38;5;81m to \033[38;5;81m it started working as expected.
Thanks to everyone else for the suggestions and help!
回答4:
Two potential things to try:
- run
stty sane
to reset the terminal settings - check the
$TERM
environment variable
来源:https://stackoverflow.com/questions/37115269/bash-printing-color-codes-literally-and-not-in-actual-color