Detailed explanation of linux tput command

Keywords: Linux Unix Operation & Maintenance cmd

1. Introduction

The tput command initializes and operates your terminal session through the terminfo database. Using tput, you can change several terminal functions, such as moving or changing the cursor, changing text properties, and clearing specific areas of the terminal screen.

Like most commands in UNIX, the tput command can be used either on the shell command line or in shell scripts. To give you a better understanding of tput, this article starts with the command line and then follows with the shell script example.

2. What is terminfo database

The terminfo database on UNIX system is used to define the properties and functions of terminals and printers, including the number of rows and columns of each device (for example, terminals and printers) and the properties of text to be sent to the device. Several common programs in UNIX rely on the terminfo database to provide these attributes and many other contents, including vi and emacs editors and curses and man programs.

Like most commands in UNIX, the tput command can be used either on the shell command line or in shell scripts. To give you a better understanding of tput, this article starts with the command line and then follows with the shell script example.

3. Parameters

(1)String output parameter settings 
  bel       Alarm bell 
  blink     Flashing mode 
  bold      bold 
  civis     hide cursor 
  clear     Clear screen 
  cnorm     Do not hide cursor 
  cup       Move cursor to screen position( x,y) 
  el        Clear to end of line 
  ell       Clear to beginning of line 
  smso      Start highlight mode 
  rmso      Stop highlight mode 
  smul      Start underline mode 
  rmul      End underline mode 
  sc        Save current cursor position 
  rc        Restore cursor to last saved position 
  sgr0      Normal screen 
  rev       Reverse view 
(2)Digital output parameter setting 
  cols      Number of columns 
  ittab     Set width 
  lines     Number of screen lines 
(3)Boolean output parameter setting 
  chts      The cursor is not visible 
  hs        With status line  
(4)scenery
   setaf ColorNumber## set foreground color 
   setab ColorNumber ##Set background color

4. Properties

4.1 cursor properties

Moving the cursor or changing cursor properties can be very useful in UNIX shell scripts or on the command line. In some cases, you may need to enter sensitive information, such as a password, or enter information in two different areas on the screen. In such cases, using tput may be helpful.

tput clear # Clear screen
tput sc # Save current cursor position
tput cup 10 13 # Move the cursor to x y
tput civis # The cursor is not visible
tput cnorm # Cursor visible
tput rc # Display the output and return to the cursor position

exit 0

4.2 moving the cursor

Using tput, you can easily move the cursor position on each device. By using the cup option or cursor position in tput, you can move the cursor to any X or Y coordinate in each row and column of the device. The coordinates in the upper left corner of the device are (0,0).

To move the cursor on the device to line 1 (Y) of column 5 (X), simply execute tput cup 5 1. Another example is tput cup 23 45, which moves the cursor to line 45 on column 23.

4.3 move cursor and display information

Another useful cursor positioning technique is to move the cursor, execute the command for displaying information, and then return to the previous cursor position:

(tput sc ; tput cup 23 45 ; echo "Input from tput/echo at 23/45" ; tput rc)

Let's analyze the subshell command:

tput sc

You must first save the current cursor position. To save the current cursor position, include the sc option or 'save cursor position'.

tput cup 23 45

After saving the cursor position, the cursor coordinates move to (23,45).

echo "Input from tput/echo at 23/45"

Displays information in stdout.

tput rc

After this information is displayed, the cursor must return to the original position saved with tput sc. to return the cursor to its last saved position, include the rc option or "restore cursor position".

Note: since this article first details how to execute tput from the command line, you may find it more concise to execute commands in your subshell than to execute each command alone and then display prompts before each command is executed.

4.4 changing cursor properties

When displaying data to a device, many times you don't want to see the cursor. Changing the cursor to invisible can make the screen look cleaner when data scrolls. To make the cursor invisible, use the civis option (for example, tput civis). After the data is fully displayed, you can use the tput cnorm option to change the cursor to visible again.

4 / 5 text attributes

Changing the display of text can make users notice a group of words in the menu or alert users to some important contents. You can change the text properties by making the text bold, adding underline below the text, changing the background color and foreground color, reversing the color scheme, etc.

To change the color of text, use the setb option (for setting the background color) and the setf option (for setting the foreground color) and the color value assigned in the terminfo database. Generally, the assigned value corresponds to the color as follows, but may vary from UNIX system to UNIX system:

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

Execute the following example command to change the background color to yellow and the foreground color to red:

tput setb 6 tput setf 4


To reverse the current color scheme, simply execute tput rev.

Sometimes, just coloring the text is not enough, that is, you want to attract the user's attention in another way. You can do this in two ways: one is to set the text to bold, and the other is to underline the text.

To change the text to bold, use the bold option. To start underlining, use the smul option. When you are finished displaying underlined text, use the rmul option.

5. Examples

5.1 variable format

#Bold
bold=$(tput bold)
#Underline
underline=$(tput sgr 0 1)
#Rules Reset 
reset=$(tput sgr0)
#gules
red=$(tput setaf 1)
#green
green=$(tput setaf 2)

5.2 make the string have color, background color and bold

#!/bin/bash
printf $(tput setaf 2; tput bold)'color show\n\n'$(tput sgr0)

for((i=0; i<=7; i++)); do
    echo $(tput setaf $i)"show me the money"$(tput sgr0)
done

printf '\n'$(tput setaf 2; tput setab 0; tput bold)'background color show'$(tput sgr0)'\n\n'

for((i=0,j=7; i<=7; i++,j--)); do
    echo $(tput setaf $i; tput setab $j; tput bold)"show me the money"$(tput sgr0)
done

exit 0

5.3 format transfer parameter output

#!/bin/bash

# $1 str       print string
# $2 color 0-7 set color
# $3 bgcolor 0-7 set background color
# $4 bold 0-1 set bold
# $5 underline 0-1 set underline

function format_output(){
    str=$1
    color=$2
    bgcolor=$3
    bold=$4
    underline=$5
    normal=$(tput sgr0)

    case "$color" in
        0|1|2|3|4|5|6|7)
            setcolor=$(tput setaf $color;) ;;
        *)
            setcolor="" ;;
    esac

    case "$bgcolor" in
        0|1|2|3|4|5|6|7)
            setbgcolor=$(tput setab $bgcolor;) ;;
        *)
            setbgcolor="" ;;
    esac

    if [ "$bold" = "1" ]; then
        setbold=$(tput bold;)
    else
        setbold=""
    fi

    if [ "$underline" = "1" ]; then
        setunderline=$(tput smul;)
    else
        setunderline=""
    fi

    printf "$setcolor$setbgcolor$setbold$setunderline$str$normal\n"
}

format_output "Yesterday Once more" 2 5 1 1

exit 0

5.4 cursor positioning output

#!/bin/bash
# clear the screen
tput clear
# Move cursor to screen location X,Y (top left is 0,0)
tput cup 3 15
# set a foreground colour using ANSI escape
tput setaf 3
echo "XYX Corp LTD."
tput sgr0
tput cup 5 17
# Set reverse video mode
tput rev
echo "M A I N - M E N U"
tput sgr0
tput cup 7 15
echo "1\. User Management"
tput cup 8 15
echo "2\. service Management"
tput cup 9 15
echo "3\. Process Management"
tput cup 10 15
echo "4\. Backup"
# Set bold mode
tput bold
tput cup 12 15
read -p "Enter your choice [1-4] " choice
tput clear
tput sgr0
tput rc

exit 0

5.5 clock countdown

  #!/bin/bash

    # tclock - Display a clock in a terminal

    BG_BLUE="$(tput setab 4)"
    FG_BLACK="$(tput setaf 0)"
    FG_WHITE="$(tput setaf 7)"

    terminal_size() { # Calculate the size of the terminal
      
      terminal_cols="$(tput cols)"
      terminal_rows="$(tput lines)"
    }

    banner_size() {

      # Because there are different versions of banner, we need to
      # calculate the size of our banner's output

      banner_cols=0
      banner_rows=0
      
      while read; do
        [[ ${#REPLY} -gt $banner_cols ]] && banner_cols=${#REPLY}
        ((++banner_rows))
      done < <(banner "12:34 PM")
    }

    display_clock() {
      
      # Since we are putting the clock in the center of the terminal,
      # we need to read each line of banner's output and place it in the
      # right spot.
      
      local row=$clock_row
      
      while read; do
        tput cup $row $clock_col
        echo -n "$REPLY"
        ((++row))
      done < <(banner "$(date +'%I:%M %p')")
    }

    # Set a trap to restore terminal on Ctrl-c (exit).
    # Reset character attributes, make cursor visible, and restore
    # previous screen contents (if possible).

    trap 'tput sgr0; tput cnorm; tput rmcup || clear; exit 0' SIGINT

    # Save screen contents and make cursor invisible
    tput smcup; tput civis

    # Calculate sizes and positions
    terminal_size
    banner_size
    clock_row=$(((terminal_rows - banner_rows) / 2))
    clock_col=$(((terminal_cols - banner_cols) / 2))
    progress_row=$((clock_row + banner_rows + 1))
    progress_col=$(((terminal_cols - 60) / 2))

    # In case the terminal cannot paint the screen with a background
    # color (tmux has this problem), create a screen-size string of 
    # spaces so we can paint the screen the hard way.

    blank_screen=
    for ((i=0; i < (terminal_cols * terminal_rows); ++i)); do
      blank_screen="${blank_screen} "
    done

    # Set the foreground and background colors and go!
    echo -n ${BG_BLUE}${FG_WHITE}
    while true; do

      # Set the background and draw the clock
      
      if tput bce; then # Paint the screen the easy way if bce is supported
        clear
      else # Do it the hard way
        tput home
        echo -n "$blank_screen"
      fi
      tput cup $clock_row $clock_col
      display_clock
      
      # Draw a black progress bar then fill it in white
      tput cup $progress_row $progress_col
      echo -n ${FG_BLACK}
      echo -n "###########################################################"
      tput cup $progress_row $progress_col
      echo -n ${FG_WHITE}

      # Advance the progress bar every second until a minute is used up
      for ((i = $(date +%S);i < 60; ++i)); do
        echo -n "#"
        sleep 1
      done
    done


Reference connection:

Posted by ultk on Thu, 18 Nov 2021 07:47:10 -0800