posix – *nix, *bsd, etc basic `tput` color setup


My goal with the below piece of POSIX shell code was to address the more platforms the better with shell tput colors. With this code, I now start all of my scripts, and so it’s time to review it for some things I overlooked, did not think of too well, and such. Note: I start my scripts with set -u, which is why I set all empty in unspecified cases. Thanks.


#!/bin/sh

set -u

if tput setaf > /dev/null 2>&1; then
    # Linux-like
    tput_number_of_colors=$(tput colors 2> /dev/null)
    tput_bold=$(tput bold 2> /dev/null)
    tput_reset=$(tput sgr0 2> /dev/null)
    tput_cmd_set_fg_color='tput setaf'
elif tput AF > /dev/null 2>&1; then
    # BSD-like
    tput_number_of_colors=$(tput Co 2> /dev/null)
    tput_bold=$(tput md 2> /dev/null)
    tput_reset=$(tput me 2> /dev/null)
    tput_cmd_set_fg_color='tput AF'
else
    # Console-like
    tput_number_of_colors=2
    tput_cmd_set_fg_color=
    tput_bold=
    tput_reset=
fi

tput_test ()
{
    ( -n "$tput_number_of_colors" ) && ( -n "$tput_bold" ) && ( -n "$tput_reset" ) &&
    { ( "$tput_number_of_colors" -ge 8 ) && printf '%s' "$tput_bold" && $tput_cmd_set_fg_color 1; } > /dev/null 2>&1
}

if tput_test; then
    color_red=$tput_bold$($tput_cmd_set_fg_color 1)
    color_green=$tput_bold$($tput_cmd_set_fg_color 2)
    color_yellow=$tput_bold$($tput_cmd_set_fg_color 3)
    color_blue=$tput_bold$($tput_cmd_set_fg_color 4)
    color_magenta=$tput_bold$($tput_cmd_set_fg_color 5)
    color_cyan=$tput_bold$($tput_cmd_set_fg_color 6)
    color_white=$tput_bold$($tput_cmd_set_fg_color 7)
else
    color_red=; color_green=; color_yellow=; color_blue=; color_magenta=; color_cyan=; color_white=
fi