在while循环内设置的shell变量在其外部不可见 [英] Shell variables set inside while loop not visible outside of it

查看:217
本文介绍了在while循环内设置的shell变量在其外部不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找包含最多字符的路径名.可能会有更好的方法来执行此操作.但我想知道为什么会出现此问题.

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_length=$(echo $line | wc -m)
    if [[ $line_length -gt $LONGEST_CNT ]] 
    then
        LONGEST_CNT=$line_length
        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中通过管道传送到while循环时,它将创建一个子外壳.子外壳程序退出时,所有变量都返回其先前的值(可以为null或未设置).可以通过使用进程替换来防止这种情况.

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循环内设置的shell变量在其外部不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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