如何从命令行检查终端颜色功能?

gav*_*koa 1 terminal bash colors bashrc

我写的:

  $ infocmp -1 xterm
        ...
    颜色#8,
    粗体=\E[1m,
    闪烁=\E[5m,
        ...
  $ tput -Txterm 颜色 && echo OK || 回声错误
8
好的
  $ tput -Txterm 闪烁 && 回声 OK || 回声错误
^[[5mOK

所以我可以使用tput来检查视网膜功能。

这个soution是便携式的吗?还有其他解决方案吗?

或者我可以坚持解决方案:

  $ [ $TERM = xterm ] && echo ok || 回声错误
好的

一种用途是在 .bashrc 中设置 PS1。另一个用于突出显示输出以引起 sh 脚本的注意。我可以使用这样的解决方案:

PS1='bash#'
案例“$TERM”在
  xterm*) PS1='\[\033[35m\]bash# \[\033[0m\]'
  ;;
esac

它只使用内置的 bash 命令(如此高效)并且适用于我的所有情况,但不幸的是不能移植。

小智 6

是的,它是便携式的。这个怎么样:

# BASH : Configure things differently if current terminal has >= 8 colors.
if which tput > /dev/null 2>&1 && [[ $(tput -T$TERM colors) -ge 8 ]]; then
    echo "Configure stuff to use colors here!"
else
    echo "No tput or less than 8 colors, default to no coloring"
fi
Run Code Online (Sandbox Code Playgroud)