|
|
In addition to printing information on the screen and redirecting the output from commands, you will almost certainly want to let your scripts prompt you for information, and make use of that information. The Bourne and Korn shells both provide the read command, which is the inverse of print or echo; it reads a line from a file (using the standard input as a default) and stores the successive words in the line in a series of shell variables which you specify on the command line. If you don't specify enough variables to hold all the words on the line read by print, all the remaining words will be stored in the last variable you name.
For example, suppose we use the following script to get a line of input from the terminal:
print Hi there! Please type a line of text.\n read foo print $fooWhen you run the script, it prompts for a line of text, and reads it all into the variable foo. The next line then prints the contents of foo. (Remember, to the shell, $foo means ``the contents associated with the variable named foo'', but foo on its own is simply a name; so the command print foo will output the word ``foo'', rather than the contents of the variable foo. This is a common pitfall when you start programming the shell.) For example, if the script above is called getline:
$The Korn shell provides a shorthand notation for this, as follows:./getline
Hi there! Please type a line of text.This is a test.
This is a test. $
read 'foo?Hi there! Please type a line of text. 'This is equivalent to the following:
print Hi there! Please type a line of text. read fooText up to the question mark is interpreted as the name of a variable in which the input is stored: text after the question mark is used as a prompt.
To read two words into different variables, you might use a script like the following:
print Hi there! Type two words then press enter.\n read foo bar print The first word I read was $foo print and the second was $barIf you type three words when you run this script, instead of two, the last two words will appear in the second variable. For example, if the script is called getwords:
$When you use the Korn shell (but not the Bourne shell) read takes a number of options. These are as follows:./getwords
Hi there! Type two words then press enter.hello yourself, program!
The first word I read was hello and the second was yourself, program! $