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
0

1 Answer 1

-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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.