为什么 xterm 显示 256 色(不是 xterm-256color)?

Kam*_*mil 11 xterm gnome-terminal

有人可以解释一下吗?我正在使用gnome-terminal. 首先,一些信息:

# echo $TERM
xterm

# infocmp xterm
Reconstructed via infocmp from file: /lib/terminfo/x/xterm
colors#8, cols#80, it#8, lines#24, pairs#64

# tput colors
8
Run Code Online (Sandbox Code Playgroud)

我编写了简单的脚本来为扩展的颜色集创建代码:

# Output file (current directory) and text.
OFILE='xterm256_colors_test.sh'
OFILE_COLORS='terminal_256_colors'
OTEXT='Sed ut perspiciatis unde omnis iste natus error sit voluptatem...'

# Clearing the contents from previous runs.
if [ -e $OFILE ] || [ -e $OFILE_COLORS ]
then
  > $OFILE
  > $OFILE_COLORS
fi

# Bang!
echo -e '#!/bin/bash\n' | tee --append $OFILE $OFILE_COLORS &> /dev/null
echo -e "\necho -e \"" | tee --append $OFILE &> /dev/null

# \x1b is a control character changing behaviour of the shell.
# It is also the <Ctrl+V><Esc> sequence.
for i in {016..255}; do
  echo -e "\x1b[38;5;${i}m $OTEXT $i \x1b[0m" >> $OFILE
  echo -e "color${i}=\"\[\033[38;5;${i}m\]\"" >> $OFILE_COLORS
done

# End of echo.
echo '"' | tee --append $OFILE &> /dev/null

# The file should be executable.
chmod +x $OFILE
Run Code Online (Sandbox Code Playgroud)

尽管xterm运行生成的脚本时有基本的终端模拟器,但我可以看到所有 240 种颜色。为什么?我想我应该$TERM改为xterm-256color第一个。

G-M*_*ca' 18

TERM环境变量是一种方式,你的用户,可以告诉程序(例如,emacsgreplessls,和vim)什么样的终端中运行了,所以他们会知道它的参数,包括哪些功能,它有什么转义序列,他们需要发出访问它们。之所以存在这种情况,是因为一般来说,软件很难自行确定这一点(当用户通过外部终端与计算机交互时几乎不可能,并且只能通过数据线连接到计算机)。

gnome-terminal是向用户提供类似终端服务的程序以及用户在终端内运行的程序。  gnome-terminal可能知道在调用之前在环境中设置的环境变量(这DISPLAY是一个明显的例子),但它不知道在其下运行的进程中设置的环境变量。

所以,gnome-terminal拥有它所拥有的任何能力。可以从外部调整/约束这些,例如,通过命令行选项、预先存在的环境、配置文件和窗口框架中的对话框,但不能通过TERM在窗口中的 shell 中进行更改。如果它能够显示 256 种颜色,那么它就能够显示 256 种颜色,您可以通过向它发送适当的转义序列来使其显示。但是,只要您TERM设置为xterm,您运行的程序就会相信您是在告诉它们它们正在一个支持八色的终端中运行, 因此它们会将它们的请求(转义序列)限制为这些功能。您需要设置TERMxterm-256color,而不是启用gnome-terminal显示256种颜色,而是告诉程序等grep,并ls要求它使用超过8种颜色。