1

可能重复:
Bash 脚本 - Do-While 循环中的变量范围

在下面的代码中,它打印了正确的iin 内部 while 循环值,但它在退出内部 while 循环后打印 0:

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
4

1 回答 1

-1

默认情况下,变量在 shell 脚本中具有全局作用域,这使“i”成为全局变量。如果您想将变量设为本地,请使用关键字“local”,例如:local i=0

有关更多详细信息,请查看链接http://www.bashguru.com/2008/06/bash-variables-scope.html

于 2012-10-03T05:45:30.600 回答