【问题标题】:Local variables after loop exit循环退出后的局部变量
【发布时间】:2011-12-13 01:40:42
【问题描述】:

退出循环后,我遇到了一些局部变量问题。尽管有以下代码,变量max 的最终值为 0:

max=0
cat tmp|while read line
do
temp=$(echo $line|tr -d "\n"|wc -c)
if [ $temp -gt $max ];then

max=$temp
echo $max
fi
done
echo -n tmp $max

cat tmp
12345
123456

这是我收到的输出:

5
6
 tmp 0

我不明白为什么 max 在退出循环后为 0,而在循环内它找到了正确的值。

【问题讨论】:

标签: bash


【解决方案1】:

管道启动一个新的子shell,它有自己的环境和变量空间。在循环结束时使用< tmp

【讨论】:

  • 是的,你说得对,我修复了它,现在它可以工作了,但我不确定管道打开新的 subshel​​ whith 变量,因为我理解它只是新命令的输入缓冲区
【解决方案2】:
max=0
while read line
do
    temp=$(echo $line|tr -d "\n"|wc -c)
    if [ $temp -gt $max ]
    then 
        max=$temp
        echo $max
    fi
done <tmp
echo -n tmp $max

【讨论】:

    【解决方案3】:

    根据 bash 手册页,管道中的每个命令都在子 shell 中执行。也就是说,您的 while 循环在子 shell 中运行,并且仅修改该子 shell 中变量 max 的值。

    子shell的变量不会传播回调用shell,它正在运行echo命令,因此仍然看到初始零值。

    如果您在同一个子shell 中运行 echo(注意花括号),它将起作用:

    max=0
    cat tmp|{
        while read line
        do
            temp=$(echo $line|tr -d "\n"|wc -c)
            if [ $temp -gt $max ];then
                max=$temp
            fi
        done
        echo -n tmp $max
    }
    

    如果您需要在外壳中进一步计算该值,则需要使用如下命令替换:

    max=0
    max=$(cat tmp|{
        while read line
        do
            temp=$(echo $line|tr -d "\n"|wc -c)
            if [ $temp -gt $max ];then
                max=$temp
            fi
        done
        echo -n $max
    })
    echo tmp $max
    

    【讨论】:

      【解决方案4】:

      while 之前的管道将循环内的所有内容放入一个单独的外壳中,因此是一个单独的标识符上下文(本质上是一个新环境)。

      通过&lt;tmp 文件重定向到while 循环将使您的循环和变量都在同一个执行上下文中。

      while read line
      do
          # your loop stuff 
      done < tmp
      

      【讨论】:

        【解决方案5】:

        这是 awk 中的一个单行代码。

        $ awk 'length>t{t=length}END{print t}' file
        6
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多