Re: Scoop of variables in While loops???

From: Alan Connor (zzzzzz_at_xxx.yyy)
Date: 04/29/05


Date: Fri, 29 Apr 2005 10:45:05 GMT

On comp.unix.shell, in
<6acda821.0504290131.285f165e@posting.google.com>,
"Sebastian" wrote:

> Hi,
>
> Why does my variables not keep the values when I exit
> the while loop below? How should I do to get them to
> keep their value after the loop is finished?
>
> COUNTER=0
> while read data_line do
>
> COUNTER=`expr $COUNTER + 1`
>
> echo $COUNTER
>
> done < files.txt
>
> echo""
> echo $COUNTER
>
> Gives the following output: 1 2 3 4 0
>
> Why?

Works fine in bash 2. What shell are you using?

I'd guess that the loop is running in a sub-shell, and
the parent shell doesn't normally inherit variable values
from its children.

You might try adding the line:

export $COUNTER
after echo $COUNTER.

If that fails, do
echo $COUNTER > /tmp/counterfileXXXXXXXXX
and read that file at the end of the script, then rm
it.

AC

-- 
alanconnor AT earthlink DOT net
Use your real return address or I'll never know you
even tried to mail me. http://tinyurl.com/2t5kp
~


Relevant Pages

  • Re: Reading a variable line by line with while loop
    ... done < `echo "$Variable"` ... echo "History - $History" ... The last echo command returns nothing, but if I put an echo command in ... the loop either before, or after the replace spaces command, it echoes ...
    (Ubuntu)
  • Re: 2.6.16-rc4: known regressions
    ... either with a command line argument, or with just the early bootup initrd ... Is there a way to tell the kernel about which is the root device other ... a loop with one second delay. ... echo -n "Waiting for root device to appear" ...
    (Linux-Kernel)
  • Re: [PHP] 2 errors I can not understand
    ... echo is not a function. ... multiple args is probably insignificant, ... and super-long loop... ... function isprime ...
    (php.general)
  • Re: problem with exit while using nohup
    ... echo "out of loop" ... loop" statement appears in the output, ... exit just gets it outside the loop but does not exit the ...   while read line ...
    (comp.unix.shell)
  • Re: Startup Script but wait for SQL to start
    ... In each case there is supposed to be a Username in the log file. ... @echo off ... if Errorlevel 1 goto Loop ... And it sucessfully starts up the Indexer. ...
    (microsoft.public.windows.server.general)