|
Home > Archive > Unix Shell > April 2005 > Scoop of variables in While loops???
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Scoop of variables in While loops???
|
|
| Sebastian 2005-04-29, 8:09 am |
| 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?
| |
| Jhair Tocancipa Triana 2005-04-29, 6:18 pm |
| Sebastian writes:
> 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
Because your shell is broken?
> cat files.txt; ./test.sh; bash --version
a
b
c
1
2
3
3
GNU bash, version 2.05b.0(1)-release (x86_64-suse-linux)
Copyright (C) 2002 Free Software Foundation, Inc.
_Please_ next time give details about your environment.
--
--Jhair
PGP key available from public servers - ID: 0xBAA600D0
| |
| Alan Connor 2005-04-29, 6:18 pm |
| 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
~
| |
| Ed Morton 2005-04-29, 6:18 pm |
|
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?
See question 36 in the FAQ (http://home.comcast.net/~j.p.h/cus-faq.html#JJ).
Ed.
|
|
|
|
|