You're viewing a comment by Cam Hutchison and its responses.

Cam Hutchison Permalink
June 04, 2012, 11:40

You have to be careful doing a read loop over stdin, as any programs inside the loop will also have their stdin attached to the same source as the read command. It occasionally produces screwy results and causes a lot of head scratching.

An alternative is to read from a different file descriptor:

exec 3< input_file.txt  # open input_file.txt on fd 3
while read -u 3 -r line ; do
    # do stuff here
exec 3<&-  # close fd 3

This potentially has the same problem because fd 3 will be inherited by the programs in the loop, but there is very little likelihood that they will try and read from it, as they may with fd 0 (stdin).

And now we're getting even further from a one-liner...

Comment Responses

June 04, 2012, 20:30

Great comment!

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "lcd_325": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.