home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 44.12 Trapping Exits Caused by Interrupts Chapter 44
Shell Programming for the Uninitiated
Next: 44.14 Putting awk, sed, etc., Inside Shell Scripts
 

44.13 read: Reading from the Keyboard

The Bourne shell read command reads a line of one or more words from the keyboard (or standard input) [5] and stores the words in one or more shell variables. This is usually what you use to read an answer from the keyboard. For example:

[5] Some early versions of read don't handle < redirection ( 13.1 ) ; they can only read from the terminal.

echo -n "Type the filename: "
read filename

  • If you give the name of one shell variable, read stores everything from the line into that variable:

    read 
    
    varname
    
    

  • If you name more than one variable, the first word typed goes into the first variable, the second word into the second variable, and so on... all leftover words go into the last variable. So, for example, with these commands:

    echo -n "Enter first and last name: "
    read fn ln

    If a user types John Smith , the word John would be available from $fn and Smith would be in $ln . If the user types Jane de Boes , then Jane would be in $fn and the two words de Boes are in $ln .

Some Bourne shells have a built-in function named line that reads a line from standard input and writes it to standard output. Use it this way:

value=`line`

The grabchars ( 45.32 ) program lets you read from the keyboard without needing to press RETURN.

- JP


Previous: 44.12 Trapping Exits Caused by Interrupts UNIX Power Tools Next: 44.14 Putting awk, sed, etc., Inside Shell Scripts
44.12 Trapping Exits Caused by Interrupts Book Index 44.14 Putting awk, sed, etc., Inside Shell Scripts

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System