Check Bash Color Printing Capability – How to Verify Terminal Colors

colorsshellterminal

I want to know if there's any way to check if my program can output terminal output using colors or not.

Running commands like less and looking at the output from a program that outputs using colors, the output is displayed wrong, like

[ESC[0;32m0.052ESC[0m ESC[1;32m2,816.00 kbESC[0m]

Thanks

Best Answer

The idea is for my application to know not to color the output if the program can't print, say, logging output from through a cron job to a file, no need to log colored output, but when running manually, i like to view the output colored

What language are you writing your application in?

The normal approach is to check if the output device is a tty, and if it is, check if that type of terminal supports colors.

In bash, that would look like

# check if stdout is a terminal...
if test -t 1; then

    # see if it supports colors...
    ncolors=$(tput colors)

    if test -n "$ncolors" && test $ncolors -ge 8; then
        bold="$(tput bold)"
        underline="$(tput smul)"
        standout="$(tput smso)"
        normal="$(tput sgr0)"
        black="$(tput setaf 0)"
        red="$(tput setaf 1)"
        green="$(tput setaf 2)"
        yellow="$(tput setaf 3)"
        blue="$(tput setaf 4)"
        magenta="$(tput setaf 5)"
        cyan="$(tput setaf 6)"
        white="$(tput setaf 7)"
    fi
fi

echo "${red}error${normal}"
echo "${green}success${normal}"

echo "${green}0.052${normal} ${bold}${green}2,816.00 kb${normal}"
# etc.

In C, you have to do a lot more typing, but can achieve the same result using isatty and the functions listed in man 3 terminfo.

Related Question