Explanation of the tput command in the shell

What is tput?

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

What is the terminfo database?

The terminfo database on UNIX systems is used to define the properties and capabilities of terminals and printers, including the number of lines and columns for each device (for example, a terminal and printer) and the properties of the text to be sent to that device. Several common programs in UNIX rely on the terminfo database to provide these properties and many others, including the vi and emacs editors and the curses and man programs.

Introduction to the tput Command Line

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

Cursor Properties

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

Moving the Cursor

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

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

Moving the Cursor and Displaying Information

Another useful cursor positioning technique is to move the cursor, execute the command used to display the 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

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 will move to (23,45).

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

the information to stdout.

After tput rc

has displayed this information, 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 executing tput from the command line, you may find it cleaner to execute commands in your own subshell than to execute each command individually and then display a prompt before each command executes.

Change the properties of the cursor

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

Text Properties

Change the way text is displayed to draw the user's attention to a set of words in a menu or to alert the user to something important. You can change text properties by making the text bold, underlining the text, changing the background and foreground colors, reversing the color scheme, and more.

To change the color of text, use the setb option (for setting the background color) and the setf option (for setting the foreground color) with the color numbers assigned in the terminfo database. Typically, assigned values ​​correspond to colors as follows, but may vary by UNIX system:

0: Black
1: Blue
2: Green
3: Cyan
4: Red
5: Magenta
6: Yellow
7: White
Execute the following example commands to change the background color to yellow and the foreground color to red:

tput setb 6
tput setf 4

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

Sometimes just coloring the text isn't enough, that is, you want to grab the user's attention in another way. This can be achieved in two ways: one is to make the text 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. Use the rmul option when you are done displaying underlined text.

Taking shell scripting to the next level

Now that you know the basics of executing tput from the command line, let's focus on applying what you've learned, along with some other features, to shell scripting. First, tput provides the following additional functions: extract terminal information (such as device, number of columns and rows) and clear data on the screen.

To determine the current number of columns (ie, the width you can use on the target device), use the cols option. To find the number of lines (that is, the current height of the line), use the lines option.

You can clear data using several methods, depending on the desired outcome. To clear data from the current cursor position to the end of the line, you can use tput el. To clear data from the current cursor position to the end of the device, you can use tput ed. If you want to clear the entire device, use tput clear.

Put it all into one script

The following code creates a basic menu. This script describes how to enhance your code in tput with several of the options described in this article.

  #!/bin/bash
trap `get_window_size` WINCH # trap when a user has resized the window

_UNDERLINE_ON=`tput smul` # turn on underline
_UNDERLINE_OFF=`tput rmul` # turn off underline

get_window_size() {
  _WINDOW_X=`tput lines`
  _WINDOW_Y=`tput cols`

  _FULL_SPACES=`echo ""|awk `
  {
    _SPACES = `${_WINDOW_Y}`
    while (_SPACES-- > 0) printf (" ")
  }'`
  _FULL_UNDERLINE=`echo "${_UNDERLINE_ON}${_FULL_SPACES}${_UNDERLINE_OFF}"`

  unset _FULL_SPACES
  show_menu

  return 0
}

set_color() {
  tput clear
  PS3="Enter Selection[1-9]:"
  select _COLOR in "Black" "Blue" "Green" "Cyan" "Red" "Magenta" "Yellow" "White" "Exit"
  do
    case ${REPLY} in
       [1-8])  _X=`expr ${REPLY} - 1`;;
           9)  break;;
           *)  echo "Invalid Color"; continue;;
    esac

    if [[ ${1} = "b" ]]
    then
      tput setb ${_X}
    else
      tput setf ${_X}
    fi
  done
}

show_menu() {
  while [[ -z ${_ANS} ]]
  do
    tput civis
    tput clear

        cat <<- EOF
                Window Size: ${_WINDOW_X} / ${_WINDOW_Y}

                Select => ${_UNDERLINE_ON}     ${_UNDERLINE_OFF}

                ${_FULL_UNDERLINE}
                B) Background Text Color
                F) Foreground Text Color

                X) Exit
        EOF

    tput rc
    tput smul
    tput cnorm

    read _ANS
    tput rmul

    case ${_ANS} in
      [Bb])  set_color "b";;
      [Ff])  set_color "f";;
      [Xx])  tput clear; exit;;
         *)
             echo -e "Invalid Selection: ${_ANS}\c"
             sleep 2
             ;;
    esac
    unset _ANS
  done
}

tput sgr0
tput civis
tput clear
tput cup 3 10
tput sc
tput cup 0 0

[[ -n ${_ANS} ]] && unset _ANS
get_window_size

exit 0

下面我们分析一下 shell 脚本。

Sets how the script is interpreted. In this example, the shell to be used is Bash. Sets a trap for the WINCH signal, specifying the get_window_size function as the trigger for the captured signal. After the trap is set, define two variables for later use when typing in the script.

#!/bin/bash
trap `get_window_size` WINCH # trap when a user has resized the window

_UNDERLINE_ON=`tput smul` # turn on underline
_UNDERLINE_OFF=`tput rmul` # turn off underline

Create a function called get_widow_size to determine Number of rows and columns. Also, define the _FULL_UNDERLINE variable, the width of the device (underlined).

get_window_size() {
  _WINDOW_X=`tput lines`
  _WINDOW_Y=`tput cols`

  _FULL_SPACES=`echo ""|awk `
  {
    _SPACES =`${_WINDOW_Y}`
    while (_SPACES--> 0) printf (" ")
  }'`
  _FULL_UNDERLINE=`echo "${_UNDERLINE_ON}${_FULL_SPACES}${_UNDERLINE_OFF}"`

  unset _FULL_SPACES
  show_menu

  return 0
}

创建一个名为 set_color 的函数来允许用户测试背景和前景文本颜色。

set_color() {
  tput clear
  PS3="Enter Selection[1-9]:"
  select _COLOR in "Black" "Blue" "Green" "Cyan" "Red" "Magenta" "Yellow" "White" "Exit"
  do
    case ${REPLY} in
       [1-8])  _X=`expr ${REPLY} - 1`;;
           9)  break;;
           *)  echo "Invalid Color"; continue;;
    esac

    if [[ ${1} = "b"]]
    then
      tput setb ${_X}
    else
      tput setf ${_X}
    fi
  done
}

Create a function called show_menu that demonstrates the size of the device. Also demonstrated in this function: turning the cursor invisible, clearing the screen, printing text, and returning to the saved cursor position.

show_menu() {
  while [[ -z ${_ANS} ]]
  do
    tput civis
    tput clear

        cat <<- EOF
                Window Size: ${_WINDOW_X} / ${_WINDOW_Y}

                Select => ${_UNDERLINE_ON} ${_UNDERLINE_OFF}

                ${ _FULL_UNDERLINE}
                B) Background Text Color
                F) Foreground Text Color

                X) Exit
        EOF

    tput rc
    tput smul
    tput cnorm

    read _ANS
    tput rmul

    case ${_ANS} in
      [Bb]) set_color "b";;
      [Ff]) set_color "f";;
      [Xx]) tput clear; exit;;
         *)
             echo -e "Invalid Selection: ${_ANS}\c"
             sleep 2
             ;;
    esac
    unset _ANS
  done
}

Next, set some basic cursor properties. First, all attributes can be cleared using sgr0. The cursor will transition to invisible and the screen will be cleared. The invisible cursor is now moved to (3,10), this position will be saved, and then the cursor will be moved to (0,0) (upper left corner).

tput sgr0
tput civis
tput clear
tput cup 3 10
tput sc
tput cup 0 0

Finally, call the get_window_size function to get the window size, and then call the function show menu.

[[ -n ${_ANS} ]] && unset _ANS
get_window_size

exit

0Conclusion

Introducing tput to shell scripts in UNIX improves the appearance of scripts. There are hundreds of ways to accomplish a task in UNIX, so why not add some color and personalization to your approach? Learning tput is easy, and can be very effective for scripting; the user will benefit from more control over the appearance of the screen. This article only serves as a guide for what you can do with tput. With tput and very little work, you can create very nice looking and comprehensive menu driven shell scripts!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326989905&siteId=291194637