Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've read that using "for" is not a good way to read lines in bash. Many people says this is clumsy and inefficient at best, and fails in many cases.

I'd like to know what is the best way to read lines in bash. Thanks.

For example:

$ for i in $(<afile); do echo "$i"; done
share|improve this question
Do you have an example of a bash script you've written using "for"? – L2G Dec 1 '11 at 17:39
for example: $ for i in $(<afile); do echo "$i"; done – Kyrol Dec 1 '11 at 17:51
up vote 16 down vote accepted

Not sure what exactly you mean, but I'm going to guess you are talking about for line in $(cat file); do* and similar constructs. This is inefficient because bash has to spawn a subshell and execute cat, read cat's output – the entire file – into memory, parse it (which is the slowest part), only then iterate over all data. Unreliable because bash performs word-splitting on the data – not only does it split on newline characters, but also on anything in $IFS (spaces, tabs...)

(If you use $(<...) instead of $(cat ...), you save two milliseconds on Linux, but all other downsides remain.)

A much better option is to use read in a while loop:

while read -r line; do
    echo "Input: $line"
done < myfile.txt

Or from a program:

cat file1 file2 file3 |
while read -r line; do
    echo "Input: $line"

This only reads as much as is needed, does not perform unnecessary processing but allows custom field splitting, and is many times faster and less resource-demanding on large files.

See also:

share|improve this answer
Very nice answer! You showed me what I wanted understand! thanks! – Kyrol Dec 2 '11 at 13:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .