Highlighting Text Output

18 Nov 2019

The linux tput command can be used to format text output in a variety of ways.  Here is a small example:

Your output may vary from the above depending on your terminal settings.

Here is the script for the above example:

Bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#! /bin/bash

err="$(tput setaf 1)$(tput smso) ERROR $(tput sgr0)"  
green_on=$(tput setaf 2)$(tput smso)  
green_off=$(tput sgr0)  

echo  
echo "  ${err} - missing value."  
echo  
echo "  Today is ${green_on}$(date +%A)${green_off}, all day long."  
echo

This follows a two-step process. First setaf sets the foreground (the text) to the desired color.  Then smso reverses everything (foreground and background) - so the background becomes the selected color, and the text takes on the color of the normal background.

Useful for when you want something to really catch the user’s eye. Use sparingly.

There’s far more to tput than I have shown here. I had no idea, just from reading the manpage.  Try this for more info.

Or how about this question and its amazing answers, regarding color values.

Cheat sheet:

setaf <value> - set ANSI foreground
setab <value> - set ANSI background
smso - start “standout” mode (reverses things, or bolds them - depends on the terminal)
sgr0 - return to normal output

This script shows the basic set of colors most terminals should be able to use:

Bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/bin/bash  

# tput_colors - Demonstrate color combinations.  

for fg_color in {0..7}  
do  
    set_foreground=$(tput setaf $fg_color)  
    for bg_color in {0..7}  
    do  
        set_background=$(tput setab $bg_color)  
        echo -n $set_background$set_foreground  
        printf ' F:%s B:%s ' $fg_color $bg_color  
    done  
    echo $(tput sgr0)  
done

Here is what I get:

The chances are good that your terminal can show millions of colors, not eight. But I only need the occasional touch, so these are fine for me.