Linux tip: Using the read command

If you write shell scripts, this is one cool builtin Linux command you should know.

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 or the publisher site,

exclamation pointflickr/kevin dooley

: Accepts User Input

A common use for user-created variables is storing information that a user enters in response to a prompt. Using

, scripts can accept input from the user and store that input in variables. The
builtin reads one line from standard input and assigns the words on the line to one or more variables:

[Five Linux predictions for 2013 and 14 of the most useful Linux websites]

$ 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

to 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
by displaying the value of firstline.

The –p (prompt) option causes

to send to standard error the argument that follows it;
does 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:

1 2 3 Page 1
ITWorld DealPost: The best in tech deals and discounts.
Shop Tech Products at Amazon