Re: Bourne Shell: scope of variables in while loop
"Doug Ritschel" <ritschel@optonline.net> writes:
> "Michal Nazarewicz" <mina86@tlen.pl> wrote in message
> news:87r6z3d27r.fsf@erwin.piotrekn...
>> "Doug Ritschel" <ritschel@optonline.net> writes:
>>
>> > i=0
>> > echo "this is a test" | while read line; do
>> > i = `expr $i + 1`
>> > done
>> > echo $i
>>
>> The while loop is run in a subshell and it has it's own local
>> variables so changing them won't change the value of oryginal
>> variable.
>
> Why, then , if I run the following, the echo prints 3, which is the
> number of lines in the hosts file.
>
> i=0
> while read line; do i=`expr $i + 1`; done < /etc/hosts
> echo $i
Because there is no need for subshell. In the first while loop you've
used a pipe so shell had to run another process. In the second while
loop you didn't use a pipe but only redirect stdout to be read from
/etc/hosts.
--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>--<jid:mina86*jabber.org>--ooO--(_)--Ooo--
|