
variable scope in a while loop (bourne shell) --- (l'il long)
Hi,
My doubt is whether the variables have any kind of scope associated with
them in a bourne shell script?
I tried the following code (the following is only a code fragment) --
--------------------
#!/bin/sh
INPUT_FILE="somefile"
FLAG=0
while read VAL
do
if [ $VAL = "x" ]
then
FLAG=1
echo $FLAG
break
fi
done < $INPUT_FILE
echo $FLAG
-------------
What I want to do here is determine the occurance of the character 'x' in
the input file. If it exists, set the flag and break from the loop. I want
to do some further processing, depending on the value of the FLAG.
But what happens here is the FLAG gets set to 1 (within the loop) when it
encounters the char 'x', but once out of the loop, it echos as '0'.
So, I was wondering if the FLAG that gets set within the while loop is local
to the loop(!!)...and goes out of scope once the loop is over.
This, however, does not happen if I use a "for VAL in `cat $INPUT_FILE"
instead of a while loop. But the problem with using the for loop is that if
the line in my input file has spaces, for loop will treat each word as an
iteration. On the other hand, using the 'while read' loop, I can read one
whole line (with spaces in it) at one go. Since my requirement is to get one
whole line in a single read, I need to use the 'while read' loop only.
It would be great if someone could clarify as to why the FLAG variable is
not able to retain its set value in the 'while read' loop but is able to
keep it if a for loop is used.
Thanks,
Aruna