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

If you are writing a custom bash script that outputs data to the terminal, standard white text on a black background is incredibly boring and difficult to read. If your script encounters a critical error, the warning message simply blends into the rest of the text. To build highly professional, visually appealing scripts, you must use the tput command to manipulate the underlying terminal capabilities, allowing you to change text colors, bold words, and even physically move the cursor around the screen.

How to Change Text Colors

The tput command does not generate text itself; instead, it sends invisible configuration codes to your terminal emulator, commanding it to alter its rendering state.

To change the color of the text, you use the setaf (Set ANSI Foreground) parameter, followed by a standard color code (0-7).

  • 0: Black
  • 1: Red
  • 2: Green
  • 3: Yellow
  • 4: Blue

If you want to print a bright red error message, run the following commands sequentially in your script:

tput setaf 1
echo "CRITICAL SYSTEM ERROR: Database failed to load."
tput sgr0

The first line tells the terminal to switch to red ink. The echo command prints the text (which now appears in bright red). The critical third line—tput sgr0—is the reset command. It instantly clears all custom formatting, ensuring your terminal returns to standard white text before the script finishes.

How to Bold and Underline Text

You can combine multiple tput commands to create highly stylized text. For example, to make a title header bold and underlined, you use the bold and smul (Start Mode Underline) parameters.

tput bold
tput smul
echo "Server Diagnostic Report"
tput sgr0

The output will be rendered with thick, bolded characters and a solid underline, instantly drawing the user’s eye to the header. Again, the sgr0 command cleanly resets the terminal immediately afterward.

How to Move the Cursor

The most advanced feature of tput is its ability to break the linear flow of the terminal by physically teleporting the cursor to specific X/Y coordinates on the screen. This allows you to build static dashboards that update in place, rather than scrolling endlessly downward.

To move the cursor, you use the cup (Cursor Position) parameter, followed by the row (Y) and column (X) numbers.

tput cup 5 20

This command silently teleports the cursor exactly 5 lines down from the top of the terminal, and 20 characters in from the left edge. Any subsequent echo command will perfectly print its text starting at that exact coordinate, allowing you to draw beautiful, structured data tables.

Get the best tech tips delivered straight to your inbox.

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