Linux tip: Using the read command

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


The read builtin returns an exit status of 0 if it successfully reads any data. It has a nonzero exit status when it reaches the EOF (end of file).

The following example runs a while loop from the command line. It takes its input from the names file and terminates after reading the last line from names.

$ cat names
Alice Jones
Robert Smith
Alice Paulson
John Q. Public

$ while read first rest
> do
> echo $rest, $first
> done < names

Jones, Alice
Smith, Robert
Paulson, Alice
Q. Public, John

The placement of the redirection symbol (<) for the while structure is critical. It is important that you place the redirection symbol at the done statement and not at the call to read.

  Sign me up for ITworld's FREE daily newsletter!

Join us:






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