bash & Ksh loop problem

hi
i was trying to optimize one script and i came across this problem .. i am putting some pseudo code here

$ >cat a.sh
ls | while read I
do
        i=$(($i + 1))
done
echo "total no of files : [$i]"

$ >ksh a.sh
total no of files : [14]

$ >bash a.sh
total no of files : []

why is bash not working ? if i use ksh to run the actual script in which arrays are used then it throws error run out of subscript ... so how can i make this thing work in bash ?

Its a side-effect of using pipes. It forks off a new process, which has its own seperate variables, causing the value to be lost when the loop completes and the pipe closes. The values are only local to things behind the pipe, so try this:

ls | (  i=0
        while read I
        do
                i=$(($i + 1))
        done
        echo "total no of files : [$i]" )

You can avoid the pipe entirely by redirecting into a temp file:

ls > /tmp/$$-ls
i=0
while read I
do
        i=$((i+1))
done < /tmp/$$-ls
rm -f /tmp/$$-ls
echo "Total no of files: [$i]"

But there's probably security problems in depending on a temp file like that.

Also, you can count lines with the wc utility.

i=$(ls | wc -l)
echo $i