tput - Linux


Overview

tput is a command used in Unix-like operating systems to manipulate terminal capabilities. Utilizing the terminfo database, tput can activate and manipulate terminal features such as color, cursor movement, text styling, and various other terminal functionalities. This command is particularly helpful in shell scripts where a dynamic and visually informative output is desired.

Syntax

The basic syntax of tput is as follows:

tput [options] capability [parameters]

Here:

  • capability refers to the specific terminal capability or feature you want to manipulate, like clear for clearing the screen or bold for bold text display.
  • parameters are optional arguments that some capabilities might require, such as the coordinates for cursor movement.

Options/Flags

tput has a few options that control its behavior:

  • -Ttype: Specifies the terminal type. If not provided, tput uses the value of the TERM environment variable.
  • -S: Allows multiple capability queries to be passed from standard input.
  • --help: Display a help message and exit.
  • --version: Output version information and exit.

Each option adjusts how tput interacts with the terminal database or how it processes commands.

Examples

  1. Clear the Screen:

    tput clear
    

    This command clears the terminal display completely.

  2. Move Cursor:

    tput cup 10 5
    

    Moves the cursor to row 10 and column 5.

  3. Set Text Color:

    tput setaf 1
    

    Changes the text color to red (color codes can vary by terminal).

  4. Enable Bold Text:

    tput bold
    

    Outputs subsequent text in bold style.

  5. Reset All Attributes:

    tput sgr0
    

    Resets all text formatting (colors, bold, underline) to default.

Common Issues

  • Incorrect Terminal Information: Errors such as unknown terminal "xterm-256color" can occur if the terminal type is misconfigured. Setting the correct TERM variable or using tput -Ttype can resolve this.

  • Capability Name Not Known: If an invalid capability name is used, tput will fail silently. Consulting the terminfo documentation for valid capability names can address this.

Integration

tput can be effectively combined with other commands in scripts to enhance script readability and interaction:

#!/bin/bash
echo "$(tput setaf 2)Green text $(tput sgr0)followed by default text."

In this example, tput is used to set part of the text output in green.

  • clear: Clears the terminal screen. Similar to tput clear but does not require terminfo.
  • setterm: Sets terminal attributes like tput, but with different options and syntax.
  • stty: Useful for changing and printing terminal line settings.

For more in-depth information about terminal capabilities and further examples, the official GNU documentation on terminfo and the NCURSES library can be a valuable resource.