Terminal Emulator – Checking How Many Colors My Terminal Supports

terminal-emulator

Is there a reliable way to check how many colors my terminal emulator supports?

If echo $TERM prints xterm, does that unequivocally tell me how many colors my terminal emulator supports? How could I check this information reliably?

Best Answer

The value of $TERM does not give much information about the number of supported colors. Many terminals advertise themselves as xterm, and might support any number of colors (2, 8, 16, 88 and 256 are common values).

You can query the value of each color with the OSC 4 ; c ; ? BEL control sequence. If the color number c is supported, and if the terminal understands this control sequence, the terminal will answer back with the value of the color. If the color number is not supported or if the terminal doesn't understand this control sequence, the terminal answers nothing. Here's a bash/zsh snippet to query whether color 42 is supported (redirect to/from the terminal if necessary):

printf '\e]4;%d;?\a' 42
if read -d $'\a' -s -t 1; then … # color 42 is supported

Among popular terminals, xterm and terminals based on the VTE library (Gnome-terminal, Terminator, Xfce4-terminal, …) support this control sequence; rxvt, konsole, screen and tmux don't.

I don't know of a more direct way.