f



bash read does not read

Can some bash expert tell me why the following does not return string:
echo string | read s; echo $s
but the following does:
echo string | while read s; do echo $s; done

Thanks,
Vinod
0
vrak58
3/7/2004 3:29:39 PM
comp.unix.shell 15484 articles. 3 followers. Post Follow

3 Replies
968 Views

Similar Articles

[PageSpeed] 1

In article <30b8645c.0403070729.2bbc2745@posting.google.com>,
 vrak58@yahoo.com (Vinod Gupta) wrote:

> Can some bash expert tell me why the following does not return string:
> echo string | read s; echo $s
> but the following does:
> echo string | while read s; do echo $s; done

The pipelined read command is executed in a subshell.  When it exits, 
its variables are lost.

-- 
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
0
Barry
3/7/2004 3:52:46 PM
Vinod Gupta <vrak58@yahoo.com> wrote:
> Can some bash expert tell me why the following does not return string:
> echo string | read s; echo $s
> but the following does:
> echo string | while read s; do echo $s; done

echo string | { read s ; echo $s; }
will work. The problem is that in a lot of shells the commands after the
'|' symbol are started in subshells, that exit as soon as they're done.
So the subshell that does the read, does know what $s is, but if you
don't use it within the same subshell, it's gone...

Using { ... } or a while loop, you have that whole block in a subshell.
You still cannot use $s outside of the while loop or { ... } block.

In real ksh and in zsh this is possible...

Zlo
0
Marc
3/7/2004 3:52:54 PM
vrak58@yahoo.com (Vinod Gupta) writes:

>Can some bash expert tell me why the following does not return string:
>echo string | read s; echo $s
>but the following does:
>echo string | while read s; do echo $s; done


Because in the first case, sub shells are executed as follows:


(echo string | read s); echo $s

(and s is not handed back to the parent)

but the whole while loop is a single sub shell.

This does echo s:

echo string | (read s; echo $s)


Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Casper
3/7/2004 4:00:58 PM
Reply: