Bash ansi escape codes

From wikinotes

Terminals are controled ansi escape sequences.
These sequences vary from terminal to terminal.
The tput command uses your terminal's termcap library to expose a common interface.


Termcap Database (portable)

See list of colours

tput looks up escape codes within the termcap database.
using tput ensures your code is portable across the unixes.

echo -e '\e[32m'     #
echo -e '\e[m'       # reset colour

tput setab 7 # set bg colour
tput setaf 7 # set fg colour
tput bold    # set bold
tput sgr0    # reset colours

yellow=$(tput setaf 3)
echo "${yellow}foo"

I usually do something like this for help text

setup_colours() {
    if [ $(tput colors) -gt 8 ] ; then
        C=$(tput setaf 6)  # code
        H=$(tput setaf 3)  # heading
        E=$(tput setaf 1)  # error
        B=$(tput bold)     # bold
        R=$(tput sgr0)     # reset
        C=$(tput sgr0)
        H=$(tput sgr0)
        E=$(tput sgr0)
        B=$(tput sgr0)
        R=$(tput sgr0)

VT220(?) non-portable

The non-portable way of handling this is as follows (but most terminals use this set of escape codes).


echo "\