5

I'm writing a shell script that I would like to use 256-color support when present. In a just world, xterm would simply set the TERM environment variable to xterm-256color and I'd use tput colors to discover the support.

But we live in an unjust world. xterm sets TERM to xterm even when launched with TERM=xterm-256color. Is there anything I can do from within a shell script to discover whether the script is running with stdout connected to a tty running in a 256-color xterm window? If so, I can set the environment variable myself.

Norman Ramsey
  • 198,648
  • 61
  • 360
  • 533

2 Answers2

2

You can check for xterm version - $XTERM_VERSION. Though I am not sure from which version xterm started to support 256 colors. Other terminals (for example gnome-terminal), behave similarly to xterm but also set COLORTERM variable to correct terminal name (gnome-256color).

Leonid Volnitsky
  • 8,854
  • 5
  • 38
  • 53
  • `XTERM_VERSION` dates from [2005](https://invisible-island.net/xterm/xterm.log.html#xterm_205), while 256-color support dates from [1999](https://invisible-island.net/xterm/xterm.log.html#xterm_112), however packages may/may not have configured that. – Thomas Dickey Sep 01 '23 at 23:11
0

Since most xterm-s are colorized these days, I would assume that the terminal has 256 colors, and make the script accept an option (perhaps -monochrome or -no-colors) otherwise.

BTW, I also see a reason for some power-user to force the -monochrome behavior: on very slow connections (think of intercontinental ssh) it might be useful to disable colors to lower the bandwidth.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547