On 2006-08-26, Doug Ritschel wrote:
>
> "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.
>>
>> In fact AFAIK the question was answered in FAQ.
>>
>>
>
> 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
First, you did not get any output from that script unless you have
an executable named 'i'. You are asking the shell to execute a
command named 'i', with arguments of '=' and '1'; you are not
incrementing a variable. You meant: i=`expr $i + 1` (no spaces
around the equals sign).
Second, you were not running it (with the error fixed) in a Bourne
shell. If you were, you would still have seen '0'. In a Bourne
shell, the redirecion alone is enough to force a subshell.
--
Chris F.A. Johnson, author <http://cfaj.freeshell.org>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence