Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
2  
See also: unix.stackexchange.com/questions/9957/… –  jasonwryan Nov 1 '11 at 17:34
add comment

3 Answers

up vote 5 down vote accepted

The value of $TERM does not give much information about the number of supported colors. Many terminals advertise themselves as xterm, and they can support any number of colors from just 2 to at least 256.

You can query the value of each color with the OSC 4 ; c ; ? BEL control sequence. If the color number c is supported, the terminal will answer back with the value of the color. If the color number is not supported, 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

I don't know of a more direct way.

share|improve this answer
    
Thanks @Gilles. This looks great. May I ask what read -d $'\a' -s -t 1 does? –  user815423426 Nov 1 '11 at 22:50
1  
@intrpc Read input until the first \a (bell character), without echoing input, with a timeout of 1 second. –  Gilles Nov 1 '11 at 22:55
2  
@l0b0 tput colors queries the terminfo database. Chances are that you have TERM=xterm. Xterm can support at least 2, 8, 16, 88 or 256 colors depending on the version and on compile- and run-time options, but the terminfo database can only store one value. You can set e.g. TERM=xterm+256color, but then you'll be annoyed when you log in to a machine that doesn't have this entry in its termcap/terminfo database. –  Gilles Nov 2 '11 at 11:59
1  
@l0b0 Your pipe obviously has nothing to do with the terminal. You need to print to the terminal (printf … >/dev/tty) and then read from the terminal (read … </dev/tty). Xterm responds to the OSC 4; …; ? BEL sequence by injecting keystrokes. –  Gilles Feb 24 '12 at 15:01
3  
Awesome, thanks! Here's a script to determine how many colors your XTerm actually supports. –  l0b0 Feb 24 '12 at 16:40
show 2 more comments

There is a perl script, 256colors2.pl, that will display all the colours on your terminal.

share|improve this answer
add comment

You can use

$ tput colors

On my debian install tput is part of the ncurses-bin package which is installed by default.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.