Returning a Single Character in a UNIX Shell Script
Ed Schaefer
How many times when programming a UNIX shell script have you wanted to echo
"Press any character to continue" without having the user press a carriage return?
Or in a shell menu, have you ever wanted to have the user choose an option without
the character being echoed? The UNIX shell doesn't provide an individual command
for returning a non-echoed single character, but manipulating the terminal driver
produces the same effect.
The terminal driver controls input between the shell script and the UNIX kernel.
The driver default is canonical or line-based mode; that is, entered characters
are buffered and not passed to the kernel until the carriage return is pressed.
To process just one character, turn off buffering by putting the terminal
in raw or single-character mode. This article presents two methods for controlling
the terminal mode; one method is a C program, and the other is a function written
in shell.
The Algorithm
Whichever method is used, the steps necessary to set raw mode, get
the character, and set back to canonical are:
1. Save original terminal settings.
2. Turn off canonical mode and echoing.
3. Get the character.
4. Reset the original terminal settings.
5. Return the character.
The ret_char C Program
The crux of the C program, shown in Listing 1, is controlling the terminal
driver with the I/O control command function, ioctl(). The three arguments
for this function are:
1. File designator - 0 for input.
2. Request - TCGETA for getting current terminal settings or TCSETA for getting
the settings.
3. termio structure - This structure contains all the information for
the terminal device. The full structure definition is in header file termio.h.
|