1

Possible Duplicate:
Bash Script - Variable Scope in Do-While loop

In the following code, it prints the correct value of i in inner while loop, but it prints 0 after it comes out of inner while loop:

string="Medicine"
for file in *
do
    i=0
    cat $file | while read line
    do
        echo $line
        if [ "$line" == "$string" ];
        then
            i=`expr $i + 1`
            echo $i
        fi
    done
    echo $i
done
Community
  • 1
  • 1
user1419742
  • 37
  • 2
  • 7

1 Answers1

-2

By default variables have global scope in shell scripting, which make "i " global. if you want to make a variable as local ,use keyword "local" , for eg: local i=0

for more details check the link, http://www.bashguru.com/2008/06/bash-variables-scope.html

Sreejith B Naick
  • 1,203
  • 7
  • 13
  • 3
    It is an error to use `local` outside a function, and you completely ignore the fact that the while loop is running in a subshell, which is the source of the poster's problem. – chepner Oct 03 '12 at 12:22