为什么我的颜色没有在所有终端中显示?

Jus*_*ner 2 colors gnome terminal

我有以下代码。

bold=''
reset=$(echo -en '\033[0m')
black=$(echo -en '\e[1;30m')
magenta=$(echo -en '\033[00;35m')
blue=$(echo -en '\e[1;34m')
cyan=$(echo -en '\e[1;36m')
green=$(echo -en '\e[1;32m')
orange=$(echo -en '\e[1;33m')
purple=$(echo -en '\e[1;35m')
red=$(echo -en '\e[1;31m')
white=$(echo -en '\e[1;37m')
yellow=$(echo -en '\e[1;33m')
lime_yellow=$(echo -en '\e[1;33m')
power_blue=$(echo -en '\e[1;34m')
blink=$(echo -en '\e[1;31m')
reverse=$(echo -en '\e[1;31m')
underline=$(echo -en '\e[1;31m')

if [ -x /usr/bin/tput ] && tput setaf 1 &>/dev/null; then
    echo "tput color is supported."
    tput sgr0 # Reset colors
    bold=$(tput bold)
    reset=$(tput sgr0)
    black=$(tput setaf 0)
    magenta=$(tput setaf 5)
    blue=$(tput setaf 33)
    cyan=$(tput setaf 37)
    green=$(tput setaf 64)
    orange=$(tput setaf 166)
    purple=$(tput setaf 125)
    red=$(tput setaf 124)
    white=$(tput setaf 15)
    yellow=$(tput setaf 136)
    lime_yellow=$(tput setaf 190)
    power_blue=$(tput setaf 153)
    blink=$(tput blink)
    reverse=$(tput smso)
    underline=$(tput smul)
else
    echo "tput color is not supported. Use old school colors."
fi

echo ${red}RED${green}GREEN${yellow}YELLOW${blue}BLUE${purple}PURPLE${cyan}CYAN${white}WHITE${reset}
Run Code Online (Sandbox Code Playgroud)

基本上有两种类型的颜色,tput生成的颜色或老式的转义字符,例如\e[1;32m. 由于tput类型更有趣,例如它支持闪烁和下划线,因此代码tput如果可能的话使用类型颜色。这是一张图像,证明它在 Oracle Linux 7.6(有点像 RedHat 或 CentOS)GUI 环境中按预期工作。

在此输入图像描述

当我从其他终端运行它时,它不起作用。例如,下面是在 MobaXterm 中运行时的快照。

在此输入图像描述

我也尝试过putty,也是不行。我的代码有什么问题吗?


更新

我在每个终端中执行echo $TERM,下面是结果。

具有桌面环境的 Oracle Linux(彩色作品)
输出:xterm-256color

Windows 上的 MobaXterm(颜色不起作用)
输出:xterm

Windows 上的腻子(颜色不起作用)
输出:xterm

Jde*_*eBP 6

使用 PuTTY或基于它的东西(例如 MobaXTerm)时,您必须将终端类型配置为putty、 、或 。它们是 terminfo 数据库中的条目正确描述 PuTTY 的唯一终端类型。putty-256colorputty-sco

人们普遍错误地认为终端仿真器都与 XTerm 兼容,并且terminfo 数据库中的xterm和条目正确地描述了它们。xterm-256color

Thomas Dickey 的 XTerm FAQ 中指出了这种错误的想法,值得注意的是xtermxterm-256color条目甚至没有描述 XTerm 的所有版本,更不用说其他终端仿真器了。

terminfo 数据库中的条目putty描述了仅支持 8 种 ECMA-48 颜色的终端。事实上,xterm条目也是如此。但仅仅从 切换xtermxterm-256colour 是错误的。PuTTY 与 XTerm 不同。

事实上,PuTTY 非常能够使用 ISO/IEC 8613 控制序列来索引颜色(调色板中的 256 种颜色)。事实上,自 2017 年以来,它非常能够使用 ISO/IEC 8613 控制序列进行直接着色(24 位 RGB 颜色)。该putty-256colour条目描述了前者。terminfo 没有办法完全描述后者。

使用正确的终端类型,tput并将查找正确的控制序列。

进一步阅读