256 Command Line Colours for the Bash Prompt (#7) and 'ls'/'dircolors'

Bash Prompt Index

The 'dircolours' Command

I dropped a hint about the availability of more than 16 colours for the Bash Prompt, and in the last couple days have been working with dircolors again: both of these use the same set of colours. This script prints out the 256 available colours and the numbers associated with each one.

#!/usr/bin/env bash
# which says this is about tput colours ... which it doesn't (directly)
# use.

bgcolour() {
    for c; do
        printf '\e[48;5;%dm %03d ' "${c}" "${c}"
    done
    printf '\e[0m \n'
}

fgcolour() {
    for c; do
        printf '\e[38;5;%dm %03d ' "${c}" "${c}"
    done
    printf '\e[0m \n'
}

IFS=$' \t\n'
echo "Base colours:"
bgcolour {0..15}
fgcolour {0..15}
echo ""
echo "More than 16 colours (fine on Mac, Fedora, probably breaks on default Debian):"
for ((i=0;i<6;i++)); do
    bgcolour $(seq $((i*36+16)) $((i*36+27)))
    fgcolour $(seq $((i*36+16)) $((i*36+27)))
    bgcolour $(seq $((i*36+28)) $((i*36+39)))
    fgcolour $(seq $((i*36+28)) $((i*36+39)))
    bgcolour $(seq $((i*36+40)) $((i*36+51)))
    fgcolour $(seq $((i*36+40)) $((i*36+51)))
done
echo ""
echo "Shades of gray (fine on Mac, Fedora, probably breaks on default Debian):"
bgcolour {232..243}
fgcolour {232..243}
bgcolour {244..255}
fgcolour {244..255}

echo ""
echo -e "Example colour gradient: \033[48;5;005m \033[48;5;201m \033[48;5;207m \033[48;5;213m \033[48;5;218m \033[48;5;224m \033[48;5;229m \033[48;5;011m \033[0m (005,201,207,213,218,224,229,011)"

This script wouldn't exist had I not found https://unix.stackexchange.com/questions/269077/tput-setaf-color-table-how-to-determine-color-codes (although I've heavily modified the script from the original). The output looks like this:

Lots of numbers and associated colour squares on a black background.

To use a colour in a Bash script - let's use "208," a shade of burnt orange I like: echo -e "\e[38;5;208morange\e[0;0m not orange". In a prompt, you have to wrap it as non-printing characters: PS1="\[\e[38;5;208m\]orange\[\e[0;0m\] not orange\\\$ ". And to use it as a dircolor setting: .txt  38;5;208.

One caveat: if this doesn't work as expected, it may be because your terminal (the Linux console, possibly a poorly configured xterm) doesn't support 256 colours.