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 point

flickr/kevin dooley

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

The –p (prompt) option causes read to send to standard error the argument that follows it; read 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:

Join us:






Spotlight on ...
Online Training

    Upgrade your skills and earn higher pay

    Readers to share their best tips for maximizing training dollars and getting the most out self-directed learning. Here’s what they said.


    Learn more

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Ask a Question