Home » tput setaf color table? How to determine color codes?

tput setaf color table? How to determine color codes?

Solutons:


The count of colors available to tput is given by tput colors.

To see the basic 8 colors (as used by setf in urxvt terminal and setaf in xterm terminal):

$ printf 'e[%sm▒' {30..37} 0; echo           ### foreground
$ printf 'e[%sm ' {40..47} 0; echo           ### background

And usually named as this:

Color       #define       Value       RGB
black     COLOR_BLACK       0     0, 0, 0
red       COLOR_RED         1     max,0,0
green     COLOR_GREEN       2     0,max,0
yellow    COLOR_YELLOW      3     max,max,0
blue      COLOR_BLUE        4     0,0,max
magenta   COLOR_MAGENTA     5     max,0,max
cyan      COLOR_CYAN        6     0,max,max
white     COLOR_WHITE       7     max,max,max

To see the extended 256 colors (as used by setaf in urxvt):

$ printf 'e[48;5;%dm ' {0..255}; printf 'e[0m n'

If you want numbers and an ordered output:

#!/bin/bash
color(){
    for c; do
        printf 'e[48;5;%dm%03d' $c $c
    done
    printf 'e[0m n'
}

IFS=$' tn'
color {0..15}
for ((i=0;i<6;i++)); do
    color $(seq $((i*36+16)) $((i*36+51)))
done
color {232..255}

256 color chart in sequence, labeled with their index


The 16 million colors need quite a bit of code (some consoles can not show this).
The basics is:

fb=3;r=255;g=1;b=1;printf 'e[0;%s8;2;%s;%s;%sm▒▒▒ ' "$fb" "$r" "$g" "$b"

fb is front/back or 3/4.

A simple test of your console capacity to present so many colors is:

for r in {200..255..5}; do fb=4;g=1;b=1;printf 'e[0;%s8;2;%s;%s;%sm   ' "$fb" "$r" "$g" "$b"; done; echo

red line, fading from darker to lighter (left-to-right)
It will present a red line with a very small change in tone from left to right. If that small change is visible, your console is capable of 16 million colors.

Each r, g, and b is a value from 0 to 255 for RGB (Red,Green,Blue).

If your console type support this, this code will create a color table:

mode2header(){
    #### For 16 Million colors use e[0;38;2;R;G;Bm each RGB is {0..255}
    printf 'e[mRn' # reset the colors.
    printf 'ne[m%59sn' "Some samples of colors for r;g;b. Each one may be 000..255"
    printf 'e[m%59sn'   "for the ansi option: e[0;38;2;r;g;bm or e[0;48;2;r;g;bm :"
}
mode2colors(){
    # foreground or background (only 3 or 4 are accepted)
    local fb="$1"
    [[ $fb != 3 ]] && fb=4
    local samples=(0 63 127 191 255)
    for         r in "${samples[@]}"; do
        for     g in "${samples[@]}"; do
            for b in "${samples[@]}"; do
                printf 'e[0;%s8;2;%s;%s;%sm%03d;%03d;%03d ' "$fb" "$r" "$g" "$b" "$r" "$g" "$b"
            done; printf 'e[mn'
        done; printf 'e[m'
    done; printf 'e[mResetn'
}
mode2header
mode2colors 3
mode2colors 4

chart of sample foreground colors with their index as labels

chart of sample background colors with their index as labels

To convert an hex color value to a (nearest) 0-255 color index:

fromhex(){
    hex=${1#"#"}
    r=$(printf '0x%0.2s' "$hex")
    g=$(printf '0x%0.2s' ${hex#??})
    b=$(printf '0x%0.2s' ${hex#????})
    printf '%03d' "$(( (r<75?0:(r-35)/40)*6*6 + 
                       (g<75?0:(g-35)/40)*6   +
                       (b<75?0:(b-35)/40)     + 16 ))"
}

Use it as:

$ fromhex 00fc7b
048
$ fromhex #00fc7b
048

To find the color number as used in HTML colors format:

#!/bin/dash
tohex(){
    dec=$(($1%256))   ### input must be a number in range 0-255.
    if [ "$dec" -lt "16" ]; then
        bas=$(( dec%16 ))
        mul=128
        [ "$bas" -eq "7" ] && mul=192
        [ "$bas" -eq "8" ] && bas=7
        [ "$bas" -gt "8" ] && mul=255
        a="$((  (bas&1)    *mul ))"
        b="$(( ((bas&2)>>1)*mul ))" 
        c="$(( ((bas&4)>>2)*mul ))"
        printf 'dec= %3s basic= #%02x%02x%02xn' "$dec" "$a" "$b" "$c"
    elif [ "$dec" -gt 15 ] && [ "$dec" -lt 232 ]; then
        b=$(( (dec-16)%6  )); b=$(( b==0?0: b*40 + 55 ))
        g=$(( (dec-16)/6%6)); g=$(( g==0?0: g*40 + 55 ))
        r=$(( (dec-16)/36 )); r=$(( r==0?0: r*40 + 55 ))
        printf 'dec= %3s color= #%02x%02x%02xn' "$dec" "$r" "$g" "$b"
    else
        gray=$(( (dec-232)*10+8 ))
        printf 'dec= %3s  gray= #%02x%02x%02xn' "$dec" "$gray" "$gray" "$gray"
    fi
}

for i in $(seq 0 255); do
    tohex ${i}
done

Use it as (“basic” is the first 16 colors, “color” is the main group, “gray” is the last gray colors):

$ tohex 125                  ### A number in range 0-255
dec= 125 color= #af005f
$ tohex 6
dec=   6 basic= #008080
$ tohex 235
dec= 235  gray= #262626

The tput utility is using a 256-color lookup table to print 8-bit ANSI escape sequences (starting with Esc and [) which makes use of terminal capabilities, so these control sequences can be interpreted as colors. These are pre-defined set of 256 colors used commonly across graphic cards.

To print all 256 colors in the terminal, try the following one-liner:

for c in {0..255}; do tput setaf $c; tput setaf $c | cat -v; echo =$c; done

Hint: Append | column to columnate list.

This 256-color lookup table can be also found at the Wikipedia page as follow:

Chart; ANSI escape code; 8-bit 256-color lookup table at Wikipedia; 256-color mode — foreground: ESC[38;5;#m   background: ESC[48;5;#m

The short answer is that you can find on the web tables of colors and match them up to the color number.

The long answer is that the correct mapping depends on the terminal —

The 125 is a parameter to an escape sequence referred to as setaf in the terminal description. tput attaches no particular meaning to the number. That actually depends upon the particular terminal emulator.

A while back, ANSI defined codes for 8 colors, and there were two schemes for numbering those. The two are seen in some terminal descriptions as the pairs setf/setb or setaf/setab. Since the latter has the connotation of “ANSI colors”, you will see that used more often. The former (setf/setb) switched the order for red/blue as noted in the ncurses FAQ Why are red/blue interchanged?, but in either case, the scheme was established for just numbering the colors. There is no predefined relationship between those numbers and RGB content.

For specific terminal emulators, there are predefined color palettes which can be enumerated easily enough — and can be programmed using these escape sequences. There are no relevant standards, and you will see differences between terminal emulators, as noted in the xterm FAQ I don’t like that shade of blue.

However, convention is often confused with standards. In development of xterm over the past 20 years, it incorporated ANSI (8) colors, adapted the aixterm feature (16) colors, added extensions for 88- and 256-colors. Much of that has been adopted by other developers for different terminal emulators. That is summarized in the xterm FAQ Why not make “xterm” equated to “xterm-256color”?.

The xterm source-code includes scripts for demonstrating the colors, e.g., using the same escape sequences that tput would use.

You may find this question/answer helpful as well: RGB values of the colors in the Ansi extended colors index (17-255)

Related Solutions

Joining bash arguments into single string with spaces

[*] I believe that this does what you want. It will put all the arguments in one string, separated by spaces, with single quotes around all: str="'$*'" $* produces all the scripts arguments separated by the first character of $IFS which, by default, is a space....

AddTransient, AddScoped and AddSingleton Services Differences

TL;DR Transient objects are always different; a new instance is provided to every controller and every service. Scoped objects are the same within a request, but different across different requests. Singleton objects are the same for every object and every...

How to download package not install it with apt-get command?

Use --download-only: sudo apt-get install --download-only pppoe This will download pppoe and any dependencies you need, and place them in /var/cache/apt/archives. That way a subsequent apt-get install pppoe will be able to complete without any extra downloads....

What defines the maximum size for a command single argument?

Answers Definitely not a bug. The parameter which defines the maximum size for one argument is MAX_ARG_STRLEN. There is no documentation for this parameter other than the comments in binfmts.h: /* * These are the maximum length and maximum number of strings...

Bulk rename, change prefix

I'd say the simplest it to just use the rename command which is common on many Linux distributions. There are two common versions of this command so check its man page to find which one you have: ## rename from Perl (common in Debian systems -- Ubuntu, Mint,...

Output from ls has newlines but displays on a single line. Why?

When you pipe the output, ls acts differently. This fact is hidden away in the info documentation: If standard output is a terminal, the output is in columns (sorted vertically) and control characters are output as question marks; otherwise, the output is...

mv: Move file only if destination does not exist

mv -vn file1 file2. This command will do what you want. You can skip -v if you want. -v makes it verbose - mv will tell you that it moved file if it moves it(useful, since there is possibility that file will not be moved) -n moves only if file2 does not exist....

Is it possible to store and query JSON in SQLite?

SQLite 3.9 introduced a new extension (JSON1) that allows you to easily work with JSON data . Also, it introduced support for indexes on expressions, which (in my understanding) should allow you to define indexes on your JSON data as well. PostgreSQL has some...

Combining tail && journalctl

You could use: journalctl -u service-name -f -f, --follow Show only the most recent journal entries, and continuously print new entries as they are appended to the journal. Here I've added "service-name" to distinguish this answer from others; you substitute...

how can shellshock be exploited over SSH?

One example where this can be exploited is on servers with an authorized_keys forced command. When adding an entry to ~/.ssh/authorized_keys, you can prefix the line with command="foo" to force foo to be run any time that ssh public key is used. With this...

Why doesn’t the tilde (~) expand inside double quotes?

The reason, because inside double quotes, tilde ~ has no special meaning, it's treated as literal. POSIX defines Double-Quotes as: Enclosing characters in double-quotes ( "" ) shall preserve the literal value of all characters within the double-quotes, with the...

What is GNU Info for?

GNU Info was designed to offer documentation that was comprehensive, hyperlinked, and possible to output to multiple formats. Man pages were available, and they were great at providing printed output. However, they were designed such that each man page had a...

Set systemd service to execute after fstab mount

a CIFS network location is mounted via /etc/fstab to /mnt/ on boot-up. No, it is not. Get this right, and the rest falls into place naturally. The mount is handled by a (generated) systemd mount unit that will be named something like mnt-wibble.mount. You can...

Merge two video clips into one, placing them next to each other

To be honest, using the accepted answer resulted in a lot of dropped frames for me. However, using the hstack filter_complex produced perfectly fluid output: ffmpeg -i left.mp4 -i right.mp4 -filter_complex hstack output.mp4 ffmpeg -i input1.mp4 -i input2.mp4...

How portable are /dev/stdin, /dev/stdout and /dev/stderr?

It's been available on Linux back into its prehistory. It is not POSIX, although many actual shells (including AT&T ksh and bash) will simulate it if it's not present in the OS; note that this simulation only works at the shell level (i.e. redirection or...

How can I increase the number of inodes in an ext4 filesystem?

It seems that you have a lot more files than normal expectation. I don't know whether there is a solution to change the inode table size dynamically. I'm afraid that you need to back-up your data, and create new filesystem, and restore your data. To create new...

Why doesn’t cp have a progress bar like wget?

The tradition in unix tools is to display messages only if something goes wrong. I think this is both for design and practical reasons. The design is intended to make it obvious when something goes wrong: you get an error message, and it's not drowned in...