我正在尝试根据错误代码打印具有特定颜色的字符串。颜色因每个错误代码而异,我将实际的颜色名称存储在变量中并在 printf 中使用它。
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
BLUE=$(tput setaf 4)
CYAN=$(tput setaf 5)
BOLD=$(tput bold)
NORMAL=$(tput sgr0)
# this color varies depending on error code
color=GREEN
printf "${$color} This is a String ${NORMAL} n"
但我得到的输出为
${GREEN} This is a String
预期输出(实际绿色(
This is a String
我可以使用
printf "${GREEN} This is a String ${NORMAL} n"
但是我希望使用颜色变量输出
Bash 不会像您尝试的那样在字符串中递归地处理${<variable>}
。
你可以做color=$<colorVariable>
,即color=$GREEN
在printf
之前,然后在printf
字符串中做"$color This is a String ${NORMAL} n"
所以,最终结果:
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
BLUE=$(tput setaf 4)
CYAN=$(tput setaf 5)
BOLD=$(tput bold)
NORMAL=$(tput sgr0)
# Event-dependant color
color=$GREEN
# And finally,
printf "$color This is a String ${NORMAL} n"
还有另一种方法可以做到这一点。
# Define all colors, only GREEN and NORMAL here for brevity reasons
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)
# Notice the missing $, as the original question
color=GREEN
# And then, use Bash's variable reference method (here notice both ! instead of $ and the missing at the beginning
printf "${!color} This is a String ${NORMAL} n"
怎么样:
color=$GREEN
然后:
printf "$color This is a String ${NORMAL} n"
给我:
This is a String
绿色。