Tuesday, February 4, 2025

Mastering tput Commands for Color Printing and Terminal Control

 `tput` is a command-line utility in Linux systems that allows you to control terminal settings, such as changing colors or setting font attributes. It provides a range of options for customizing your output and enhancing the user experience.

In this guide, we'll explore the various features of `tput`, including color printing, font styles, cursor positioning, and more. Whether you're a developer looking to create visually

appealing command-line interfaces (CLI) or a system administrator seeking to improve terminal usability, this article will equip you with the knowledge necessary to harness the full potential of `tput`.

Color Printing with tput

To print colored output using `tput`, you need to specify color codes in the format recommended by the terminal being used. Most terminals support ANSI escape sequences, which allow for text formatting and changing colors among other things.

Color Codes

*   Foreground colors: 30-37 (red through white), 90-97 (bright red through bright white)

*   Background colors: 40-47 (red through white), 100-107 (bright red through bright white)

Example Code for Color Printing

tput setaf 1 # red
echo "Hello"

tput setab 4 # blue background
echo "World"

Resetting Colors with tput

To reset the colors after printing, use `tput sgr0` or `tput reset`. This command resets all attributes back to default (color, font style, etc.).

Example Code for Resetting Colors

tput setaf 1; echo "Hello"; tput sgr0 # resets color after printing

Additional Features of tput


In addition to color printing and resetting colors, `tput` offers various other features that can be used to enhance the user experience.

Setting Bold Text


`tput bold`: Makes text appear in a bold font.


tput bold; echo "Bold text"; tput sgr0 # sets text to bold and resets later


Setting Italic Text (Supported by Some Terminals)


`tput sitm` or `tput rmso`: Not all terminals support italic formatting, so use with caution. To reset the font style back to normal, use `tput rmso`.


Setting Underline Text (Supported by Some Terminals)

`tput smul` or `tput rmul`: Not all terminals support underlining, so use with caution. To reset the font style back to normal, use `tput rmul`.

Clearing Screen


`tput clear`: Clears the entire screen of any output.

tput clear
echo "New content here"


Cursor Control with tput


`tput civis` or `tput cvvis`: Hides or shows the cursor from view.

tput civis; echo "Hidden"; tput cvvis # hides and shows the cursor

No comments: