将变量的值传播到循环外部 [英] Propagate value of variable to outside of the loop

查看:70
本文介绍了将变量的值传播到循环外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dpkg --list |grep linux-image |grep "ii  " | while read line
do
  arr=(${line})
  let i=i+1
  _constr+="${arr[2]} "
done
echo $i
echo ${_constr}

循环外的echo语句不显示预期的变量.

The echo statements outside of the loop do not display the expected variables.

如何使变量的内容在循环外传播?

How should I make the contents of the variable propagate outside the loop?

推荐答案

问题出在管道上,而不是循环上.尝试这种方式

The problem is the pipe, not the loop. Try it this way

let i=0
declare -a arr

while read -r line ; do
    arr=(${line})
    let i=i+1
    _constr+="${arr[2]} "
done < <(dpkg --list |grep linux-image |grep "ii  ")

echo $i
echo ${_constr}

为清楚起见,您还应该预先声明全局变量,如上所示.

You should also pre-declare globals for clarity, as shown above.

如布拉戈维斯特在评论中所指出的那样,管道是在一个子外壳中执行的.使用流程替代(这是< <(commands)语法)将所有内容保持在同一过程中,因此可以更改全局变量.

Pipes are executed in a subshell, as noted by Blagovest in his comment. Using process substitution instead (this is the < <(commands) syntax) keeps everything in the same process, so changes to global variables are possible.

顺便说一句,您的管道也可以得到改善

Incidentally, your pipeline could be improved as well

dpkg --list |grep '^ii.*linux-image'

不必担心grep的调用.

这篇关于将变量的值传播到循环外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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