Grabbing information about the terminal
While writing command-line shell scripts, we will often need to heavily manipulate information about the current terminal, such as the number of columns, rows, cursor positions, masked password fields, and so on. This recipe helps in collecting and manipulating terminal settings.
Getting ready
tput
and stty
are utilities that can be used for terminal manipulations. Let us see how to use them to perform different tasks.
How to do it...
There are specific information you can gather about the terminal as shown in the following list:
Get the number of columns and rows in a terminal by using the following commands:
tput cols tput lines
To print the current terminal name, use the following command:
tput longname
To move the cursor to a 100,100 position, you can enter:
tput cup 100 100
Set the background color for the terminal using the following command:
tputsetb n
n
can be a value in the range of 0 to 7.Set the foreground color for text by using the following command:
tputsetf n
n
can be a value in the range of 0 to 7.To make text bold use this:
tput bold
To start and end underlining use this:
tput smul tput rmul
To delete from the cursor to the end of the line use the following command:
tputed
While typing a password, we should not display the characters typed. In the following example, we will see how to do it using
stty
:#!/bin/sh #Filename: password.sh echo -e "Enter password: " stty -echo read password stty echo echo echo Password read.
Note
The
-echo
option in the preceding command disables the output to the terminal, whereasecho
enables output.