从问题while循环中访问一个全局变量 [英] Problem accessing a global variable from within a while loop

查看:1534
本文介绍了从问题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

这篇关于从问题while循环中访问一个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆