Unix for Mac OS X 10.4 Tiger: Visual QuickPro Guide (2nd Edition)
You've seen one way to get user input into your scriptsby using the command-line arguments and then accessing them with $1 , $ 2 , and so on, or $@ . But what if you want your script to ask the user for input while it is running? No problemyou use the read command.
Refer to Figure 9.34 while reading the following task. Figure 9.34 is a code listing of a script that asks the user for input and stores the input in a variable. Figure 9.35 shows the script being used.
Figure 9.34. Code listing of a script using the read command to get user input.
#!/bin/sh # This script asks the user for input and stores it in a variable. echo "Hello $USER, we just want to ask you a few questions." # Use the -n option to echo to suppress the new line echo -n "Enter an integer: " read number square=`expr $number \* $number` echo "The square of $number is $square"
Figure 9.35. Output from the script in Figure 9.34.
localhost:~ vanilla$ ./read.sh Hello vanilla, we just want to ask you a few questions. Enter an integer: 7 The square of 7 is 49 [localhost:~] ./read.sh Hello vanilla, we just want to ask you a few questions. Enter an integer: 17 The square of 17 is 289 localhost:~ vanilla$
To read user input into a variable:
- read variable
The read command takes one or more arguments that are the names of variablesfor example,
read var1 var2 var3
When executed, read waits for user input and reads a line of input from the keyboard (actually from stdin see Chapter 2 for more on standard input).
read splits the input into pieces, based on the spaces between words, and stores each piece in one of the variables .
If there are more pieces (input) than variables, the extras go in the last variable. This means that if you use read with a single variable name , you get an entire line of user input in that one variable. If there are more variables than input, the extra variables are left empty. If the script has
read var1 var2 var3
and the user types
good morning
then var1 will contain good , var2 will contain morning , and var3 will be empty.