我想更改一个程序以自动检测终端是否支持颜色,因此当我从不支持颜色的终端(例如(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/