微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,那将是巨大的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐