This content is excerpted from the new 3rd Ed. of 'A Practical Guide to Linux: Commands, Editors, and Shell Programming', authored by Mark Sobell, ISBN 013308504X, published by Pearson/Prentice Hall Professional, Sept. 2012, Copyright 2013 Mark G. Sobell. For more info please visit www.sobell.com or the publisher site, www.informit.com
read: Accepts User Input
A common use for user-created variables is storing information that a user enters in response to a prompt. Using
read, scripts can accept input from the user and store that input in variables. The
readbuiltin reads one line from standard input and assigns the words on the line to one or more variables:
$ cat read1 echo -n "Go ahead: " read firstline echo "You entered: $firstline" $ ./read1 Go ahead: This is a line. You entered: This is a line.
The first line of the read1 script uses
echoto prompt for a line of text. The –n option suppresses the following NEWLINE, allowing you to enter a line of text on the same line as the prompt. The second line reads the text into the variable firstline. The third line verifies the action of
readby displaying the value of firstline.
The –p (prompt) option causes
readto send to standard error the argument that follows it;
readdoes not terminate this prompt with a NEWLINE. This feature allows you to both prompt for and read the input from the user on one line:
$ cat read1a read -p "Go ahead: " firstline echo "You entered: $firstline" $ ./read1a Go ahead: My line. You entered: My line.
The variable in the preceding examples is quoted (along with the text string) because you, as the script writer, cannot anticipate which characters the user might enter in response to the prompt. Consider what would happen if the variable were not quoted and the user entered
*in response to the prompt: