在您输出任何颜色之前,您需要确保您在终端:[ -t 1 ] && echo 'Yes I am in a terminal' # isatty(3) call in C
然后,如果支持颜色,则需要检查终端功能
在具有terminfo (基于Linux)的系统上,您可以获得支持的颜色数量Number_Of_colors_Supported=$(tput colors)
在具有termcap (基于BSD)的系统上,您可以获得支持的颜色数量Number_Of_colors_Supported=$(tput Co)
然后让你决定:[ ${Number_Of_colors_Supported} -ge 8 ] && {
echo 'You are fine and can print colors'} || {
echo 'Terminal does not support color'}
顺便说一下,不要像以前用ESC字符那样使用着色。使用标准调用终端功能,为您分配特定终端支持的CORRECT颜色。
基于BSDfg_black="$(tput AF 0)"fg_red="$(tput AF 1)"fg_green="$(tput AF 2)"fg_yellow="$(tput AF 3)"fg_blue="$(tput AF 4)"fg_magenta="$(tput AF 5)"fg_cyan="$(tput AF 6)"fg_white="$(tput AF 7)"reset="$(tput me)"
基于Linuxfg_black="$(tput setaf 0)"fg_red="$(tput setaf 1)"fg_green="$(tput setaf 2)"fg_yellow="$(tput setaf 3)"fg_blue="$(tput setaf 4)"fg_magenta="$(tput setaf 5)"fg_cyan="$(tput setaf 6)"fg_white="$(tput setaf 7)"reset="$(tput sgr0)"
用于echo -e "${fg_red} Red ${fg_green} Bull ${reset}"