Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 1997 > 9704

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.




MarketPlace

Instant Answers to Your IT & Business Questions
Sign Up & Get Full Access To The Definitive Online Book Collection With SkillSoft's Books24x7�.

Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.

Online Crash Analysis
Automatically capture customer crash data, no debugger required. Support for .NET, C++, OS X, Java.

WinDev 11 - Powerful IDE
Develop 10 times faster ! ALM, IDE, .Net, RAD, 5GL, Database, 5GL, 64-bit, etc. Free Express version

Wanna see your ad here?