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.
#!/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"
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: