0

I am trying to make my shell script supporting as much terminals as possible, that is, adding ANSI colors, bold and dim only when supported. However, I want to detect the number of colors supported. We can use tput colors.

However, I find that some systems that are stripped down to minimal does not have it installed. So, I want to implement it in shell.

How does tput colors work? Any equivalent of tput colors with POSIX commands? Please help and answer.

6
  • A similar question posted today: How to know if the terminal understands '\033[2J\033[H'? Commented Jan 6, 2023 at 13:00
  • minimal systems won't have bash either. Commented Jan 6, 2023 at 13:21
  • Definition of "minimal": suse.com/suse-defines/definition/minimal-operating-system Commented Jan 6, 2023 at 13:33
  • Even many full blown operating systems won't have bash either. bash is the GNU shell, it's only used on GNU systems and a few non-GNU ones. Commented Jan 6, 2023 at 13:35
  • 1
    I think we are off topic debating whether Bash is installed on different operating systems XD... Lets remove these comments. Commented Jan 6, 2023 at 13:37

1 Answer 1

0

tput queries the termcap or terminfo database based for the terminal whose name is stored in $TERM.

tput is a standard command, but the names of the capabilities except for clear, init and reset (in the POSIX locale only) are not specified.

If some systems don't have tput, they likely don't have a terminfo or termcap database either.

Also beware that terminal names are not standardised.

For instance, there are many terminals that set $TERM to xterm even though they don't implement the xterm API fully or properly, and there are many versions of xterm, and xterm can be compiled or configured with support for different numbers of colours with that not being always reflected in the value of $TERM, not to mention that the shades of the various colours even for those that use the same escape sequences vary from one terminal to the next, so it's not an exact science.

On systems that don't have terminfo/termcap databases, you'd have to ship your own database (maybe a subset with the most commonly used terminals, and only the capabilities of interest) and implement a way to query it from your script.

At the very least, that could be just a big case construct:

case $TERM in ( fbterm ) colors=256 fg_color() { printf '\33[1;%sd}' "$1"; } ;; ( *256color* | alacritty | i[tT]erm* ) colors=256 fg_color() { if [ "$1" -lt 8 ]; then printf '\33[3%sm' "$1" elif [ "$1" -lt 16 ]; then printf '\33[9%sm' "$(( $1 - 8 ))" else printf '\33[38;5;%sm' "$1" fi } # and so on. esac 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.