unix – 如何确定终端是否具有颜色能力?

我想更改一个程序来自动检测终端是否具有颜色能力,所以当我从一个无色能的终端(比如(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.
$

这是…次优。

一个朋友指着我(t)(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,那将是巨大的。

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...