while loop and variables in shelll script...

I'm having a problem returning variables from a loop. the variable test get incremented each time it goes through the loop but if I try to get the count after the loop has run I get 0. Can anyone explain to me why this is happening and maybe show the correct way to go about doing this?

BTW I'm using MOSX 10.2 and running the script in sh

#!/bin/sh
test=0
var="file"
ls=/bin/ls

ls | while read fn ;
do
echo $fn;
if [ $? == 0 ]; then
test=$((`expr $test + 1`))
echo $test;
fi;
done

echo $test

sh is running the while loop in a subshell. Variables changed in the subshell do affect the values in the main shell.

ksh won't do that. Switch to ksh.

And ksh can increment the variable directly:
((test=test+1))

I'm not familiar with MOSX, but you have an odd version of sh if that script really runs.

You will probably need to switch the == to just = (or -eq) in your if statement. And I'm not sure why you're checking the exit code from the echo statement anyway. Are you actually finding filenames that your echo command cannot output?

This is a small part of a larger script. I used the ls command to simplify the script for the purpose of solving the assignment problem.

It's just the test varible not being set by the assignments in the loop.

Is there any way to do this in sh?

#!/bin/sh
counter=0
x=0
cat file | while read LINE
do
echo $LINE
let x=$x+1
echo $x (increments like it's supposed to)
done

echo the $x (returns 0)

Can someone explain how to get the variable outside the loop to refelct the variable inside the loop?

Switch to a better shell. ksh will not run the inner loop in a subshell. The best anser that I can give for the old sh shell is to write the variable into a file each iteration. Once the loop is finished, read the file to set your variable. Expect that to slow down your script a lot.

Surely you have ksh or bash available. You really need to use a better shell.

I believe bash is available in MOSX 10.2 by default.
But I do prefer ksh - the first software I added to my system when I got it was ksh. You can get a binary here: