setf/setaf or how to portably add colors to your prompt

There are a million pages on the web that describe how to make your bash prompt nice and colorful. Most just hard-code the color sequences, which can break if you use a weird terminal. Until today I used some clever code I stole from somewhere that used tput to get the color codes from the termcap/terminfo database. Today I learned that there are two “standard” capabilities for setting colors: setf and setaf. I’m not sure why both exist, but some terminals only support one and not the other. (Notably Terminator only supports setaf.) So here’s what’s in my .bashrc to deal with this variety:

_tput() {
   tput $* 2> /dev/null
}
# Color definitions.
blue=`_tput setf 1 || _tput setaf 4`
green=`_tput setf 2 || _tput setaf 2`
cyan=`_tput setf 3 || _tput setaf 6`
red=`_tput setf 4 || _tput setaf 1`
magenta=`_tput setf 5 || _tput setaf 5`
yellow=`_tput setf 6 || _tput setaf 3`
white=`_tput setf 7 || _tput setaf 7`
default_colors=`_tput op`
bold=`_tput bold`
# clear all attributes
plain=`_tput sgr0`
prompt="$"
prompt_color=$cyan
# removed code that changes prompt_color depending on some conditions
# Check for being root.
if [ `whoami` == "root" ]; then
    prompt="#"
    ps1_user="\[$red\]\u\[$prompt_color\]"
else
    ps1_user="\[$prompt_color\]\u"
fi
PS1="${ps1_user}@\h:\w$prompt\[$default_colors$plain\] "

About the author

Living the good life in Seattle, occasionally sharing something interesting with the Internet.