击 - 传播变量的值,以在循环的外侧 [英] Bash - propagate value of variable to outside of the loop

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

问题描述

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}

您也应该$ P $为清楚起见,对全局声明如上图所示。

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

管道在子shell执行,由Blagovest在他的评论中指出。使用进程替换,而不是(这是&LT; &所述;(命令)语法)保持在​​同一进程中的一切,所以改变全局变量是可能的

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天全站免登陆