Search code examples
bashshellterminfotput

Color codes for tput setf


I am sourcing a file with this content

export fgBlack8="$(tput setf 0)";
export fgRed8="$(tput setf 1)";
export fgGreen8="$(tput setf 2)";
export fgYellow8="$(tput setf 3)";
export fgBlue8="$(tput setf 4)";
export fgMagenta8="$(tput setf 5)";
export fgCyan8="$(tput setf 6)";
export fgWhite8="$(tput setf 7)";

export bgBlack8="$(tput setb 0)";
export bgRed8="$(tput setb 1)";
export bgGreen8="$(tput setb 2)";
export bgYellow8="$(tput setb 3)";
export bgBlue8="$(tput setb 4)";
export bgMagenta8="$(tput setb 5)";
export bgCyan8="$(tput setb 6)";
export bgWhite8="$(tput setb 7)";

according to this link: https://linux.101hacks.com/ps1-examples/prompt-color-using-tput/

Then, when testing the Colors with a few commands like this

echo -e "${fgBlack8}fgBlack8"
echo -e "${fgRed8}fgRed8"
echo -e "${fgGreen8}fgGreen8"
echo -e "${fgYellow8}fgYellow8"
echo -e "${fgBlue8}fgBlue8"
echo -e "${fgMagenta8}fgMagenta8"
echo -e "${fgCyan8}fgCyan8"
echo -e "${fgWhite8}fgWhite8"

I receive the following output:

Colors scrambled

Displaying red as blue, yellow as cyan and vice versa. Are the codes on the website wrong or am I using it wrong and produce correct Color mappings by accident?


Solution

  • If you are using tput command, then it's logical to start with

    $ man tput
    

    which from SEE ALSO will take you to

    $ man terminfo
    

    and you'll discover that

    The setaf/setab and setf/setb capabilities take a single numeric argu- ment each. The terminal hardware is free to map these as it likes, but the RGB values indicate normal loca- tions in color space.

                    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
    

    The argument values of setf/setb historically correspond to a different mapping, i.e.,

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