Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with "read from pipe"

Status
Not open for further replies.

sbix

IS-IT--Management
Nov 19, 2003
493
0
0
CA
Hi everybody,
I am having a strange problem.
If I write something like:
cat file_of_data | while read x
do
BLAH BLAH BLA
done
echo "x=$x"


I have this output "x="

If I write, WITHOUT CHANGING ANYTHING IN file_of_data:
while read x
do
BLAH BLAH BLAH
done < file_of_data
echo "x=$x"


The output is "x=last_value_read".
Looks like a sudden death of the process writing in the pipe whipes out in the variables changed in the do... done block
Any idea?
 
Yes, this is an annoying problem which occurs in some shells but not others, and it is the reason why I usually advocate using the second syntax.

When the shell in question creates a pipe it actually forks 2 processes, a reader and a writer. So when those processes finish, any variables that were set while they were running are lost.

No extra processes are forked to handle a redirection, hence the variables you set are retained.

Annihilannic.
 
Annihilannnic, I see what you say... the do.. BLAH BLAH.. done process is ran in a different process in a proper space when reading from a pipe...
It sounds... but it means also that legions of scripts wont run with this impementation of shell...
Thanks a lot
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top