bash 支持 ansi 转义码。我想在脚本中使用一些漂亮且漂亮的测试打印。因为我没有找到任何提供此功能的基本内置\lib ool\脚本,看来我必须在名称和转义码之间使用硬编码映射,例如
RESET="0"
BOLD="1"
FAINT="2"
ITALIC="3"
# etc.
FG_RED="31"
BG_RED="41"
是否有任何内置\lib ool\脚本可以提供简单的界面/工具/lib/等。在bash中使用ansi颜色和效果?如果没有,我怎样才能以某种方式检索映射?
我通常会在脚本顶部放置类似的内容..
# print color (no previous dependency on setting colors)
#---------------------------------
# color formatting and stuff
#---------------------------------
# print a string in color, with no \n
# e.g. printcn red "some text"
printcn() {
local m="${*:-$(read -t 0.01 m; echo "${m}")}"
#local m="${@}"
local c="${m%% *}" # color would be in first word
# see if first word (lowercase) matches a color
case "${c,,}" in
-n|nc|norm|normal) m="$(tput sgr0 )${m#* }" ;;
-r|red) m="$(tput setaf 1)${m#* }" ;;
-g|grn|green) m="$(tput setaf 2)${m#* }" ;;
-y|yel|yellow) m="$(tput setaf 3)${m#* }" ;;
-b|blu|blue) m="$(tput setaf 4)${m#* }" ;;
-m|mag|magenta) m="$(tput setaf 5)${m#* }" ;;
-c|cya|cyan) m="$(tput setaf 6)${m#* }" ;;
-w|whi|white) m="$(tput setaf 7)${m#* }" ;;
esac
printf -- '%s' "${m}$(tput sgr0)"
} >&2
# Print color with newline
printc() {
local in
in="${*:-$(read -t 0.01 in; echo "${in}")}"
printcn "${in}"; printf '\n'
} >&2
然后我可以做这样的事情:
printc -r this is red text
printc blue "This is blue"