How to Format Terminal Text Colors Using the tput Command in Linux

When you are writing a complex bash script that outputs paragraphs of text to the terminal, presenting that text in a uniform, unformatted block makes it incredibly difficult for the user to read. Important error messages blend in with standard informational output. While you can technically use raw ANSI escape codes (like \e[31m) to format your text, those codes are difficult to memorize, visually messy, and not universally supported across all terminal emulators. The correct, portable way to control terminal output formatting in Linux is by using the tput command.

How the tput Command Works

The tput utility queries the terminfo database. Instead of hard-coding raw escape sequences into your script, you ask tput for a specific capability (like “make the text bold” or “change the text to red”). tput determines what kind of terminal the user is running and outputs the correct sequence dynamically, guaranteeing compatibility.

To use it inside a bash script, you generally assign the output of tput to a variable using command substitution.

Changing Text Colors

To change the color of the foreground text, you use the setaf (set ANSI foreground) capability, followed by a color index number (0 through 7).

  • 0 = Black
  • 1 = Red
  • 2 = Green
  • 3 = Yellow
  • 4 = Blue
  • 5 = Magenta
  • 6 = Cyan
  • 7 = White

For example, to print a critical error message in bold red text, you would write this in your script:

RED=$(tput setaf 1)
NORMAL=$(tput sgr0)

echo "${RED}CRITICAL ERROR: Database connection failed.${NORMAL}"

Crucial Step: Notice the tput sgr0 command. This stands for “set graphics rendition to 0” (reset). You must reset the terminal formatting at the end of your echo statement. If you do not reset it, every single command typed into the terminal after your script finishes will also be bright red.

Applying Text Formatting (Bold and Underline)

You can also use tput to apply typographic emphasis to your text without changing the color.

  • Bold text: Use the bold capability.
    BOLD=$(tput bold)
    echo "Please enter your ${BOLD}username${NORMAL} below:"
  • Underlined text: Use the smul (start mode underline) capability. To turn it off without resetting the entire terminal color, use rmul (remove mode underline).
    UNDERLINE=$(tput smul)
    NO_UNDERLINE=$(tput rmul)
    echo "Read the ${UNDERLINE}documentation${NO_UNDERLINE} before proceeding."

Clearing the Screen

While you can use the standard clear command, you can also use tput to clear the terminal screen before printing your formatted output, which is especially useful when drawing text-based user interfaces.

tput clear
echo "Welcome to the installation wizard."

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.