从问题while循环中访问一个全局变量

问题描述:

我试图找到其中的大多数角色的路径名。可能有更好的方式来做到这一点。不过,我想知道为什么会出现此问题。

I am trying to find the pathname with the most characters in it. There might be better ways to do this. But I would like to know why this problem occurs.

LONGEST_CNT=0
find samples/ | while read line
do
    line_lenght=$(echo $line | wc -m)
    if [[ $line_lenght -gt $LONGEST_CNT ]] 
    then
        LONGEST_CNT=$line_lenght
        LONGEST_STR=$line
    fi
done

echo $LONGEST_CNT : $LONGEST_STR

这在某种程度上总是返回:

It somehow always returns:

0 :

如果我打印结果为while循环调试值是否正确。那么,为什么bash中不会使这些变量全局?

If I print the results for debugging inside the while loop the values are correct. So why bash does not make these variables global?

在Bash中你管到,而循环,它会创建一个子shell。当子shell退出时,所有变量返回自己的previous值(可能为null或取消)。这可以通过使用进程替换pvented $ P $。

When you pipe into a while loop in Bash, it creates a subshell. When the subshell exits, all variables return to their previous values (which may be null or unset). This can be prevented by using process substitution.

LONGEST_CNT=0
while read -r line
do
    line_length=${#line}
    if (( line_length > LONGEST_CNT ))
    then
        LONGEST_CNT=$line_length
        LONGEST_STR=$line
    fi
done < <(find samples/ )    # process substitution

echo $LONGEST_CNT : $LONGEST_STR