unix - 如何确定终端是否支持颜色?

标签 unix terminal termcap terminfo

我想更改一个程序以自动检测终端是否支持颜色,因此当我从不支持颜色的终端(例如(X)Emacs中的Mx shell)运行该程序时,颜色会自动关闭。

我不想对程序进行硬编码以检测TERM = {emacs,dumb}。

我认为termcap / terminfo应该可以解决这个问题,但到目前为止,我仅设法使用代码片段将这(n)个诅咒拼凑在一起,当找不到终端时,它会严重失败:

#include <stdlib.h>
#include <curses.h>

int main(void) {
 int colors=0;

 initscr();
 start_color();
 colors=has_colors() ? 1 : 0;
 endwin();

 printf(colors ? "YES\n" : "NO\n");

 exit(0);
}

即我得到这个:
$ gcc -Wall -lncurses -o hep hep.c
$ echo $TERM
xterm
$ ./hep
YES
$ export TERM=dumb
$ ./hep           
NO
$ export TERM=emacs
$ ./hep            
Error opening terminal: emacs.
$ 

这是次优的。

最佳答案

一个 friend 将我指向tput(1),我准备了以下解决方案:

#!/bin/sh

# ack-wrapper - use tput to try and detect whether the terminal is
#               color-capable, and call ack-grep accordingly.

OPTION='--nocolor'

COLORS=$(tput colors 2> /dev/null)
if [ $? = 0 ] && [ $COLORS -gt 2 ]; then
    OPTION=''
fi

exec ack-grep $OPTION "$@"

这对我有用。不过,如果我有一种方法可以将其集成到ack中,那就太好了。

关于unix - 如何确定终端是否支持颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2465425/

相关文章:

unix - 如何让我的 dockerized Go 程序在默认端口上使用 dockerized Redis?

linux - 在 ubuntu 中使用灯服务器

ubuntu - 如何卸载/usr 文件夹中的软件包

java - 从 java 调用简单的 shell 脚本不起作用

c - 在终端中实现覆盖

java - "kill -QUIT"是否真的杀死了 JVM?

linux - 在bash中执行任意命令

python - Visual Studio Code 在同一终端中运行代码

使用 TermCaps 捕捉箭头键

c - 在反引号之间执行的程序的 termcap