Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to maintain variable value set in while do loop - sh shell

Status
Not open for further replies.

gotchausa

Programmer
Jan 24, 2002
64
CA
Hi,

I've got a Bourne .sh script that has a while do loop. Pseudo code as follows:

x=0
while x<10
do
echo x
x=x+1
done

echo &quot;last value of x is $x&quot;

The last echo statement returns 0. Is there a way to get the value of x from the last invocation of the while loop i.e x=9???
 
Real code ...
Code:
x=0
while [ $x -lt 10 ]
do
echo $x
x=`expr $x + 1`
done

echo &quot;last value of x is $x&quot;
Greg.
 
the following works fine:

#!/bin/sh

x=0
while [ &quot;$x&quot; -lt 10 ]
do
x=`expr $x + 1`
done

echo &quot;$x&quot;
vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Thx. Thats works fine. However, when I do something like this..

x=0
while read each line
do
# SKIP BLANK LINES.
y=`echo ${each_line} | wc -w`
if [ $y != 0 ]
then
echo &quot;blah&quot;
x=`expr $x + 1`
fi
done < /tmp/test.txt

echo $x

Now x should return something other than 1 if there are noblank lines in the file being read in. But the result is always 0.
When I do an echo on $x within the while loop, I see that it gets incremented to 1. When the loop exits, x is 0 again...
 
Bourne is old - migrate to Korn ;)

here's one way to do it in Bourne [UUOC included]:

#!/bin/sh
#set -x

x=0
cat /tmp/test.txt | { while read each_line
do
# SKIP BLANK LINES.
y=`echo ${each_line} | wc -w`
if [ $y -ne 0 ]
then
x=`expr $x + 1`
fi
echo &quot;INSIDE->[$x]&quot;
done
echo &quot;OUTSIDE->[$x]&quot;
}
vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top