将变量的值传播到循环外部
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 语句不显示预期的变量。
我应该如何使变量的内容传播到循环之外?
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}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题出在管道上,而不是环路上。尝试这种方式
管道是在子 shell 中执行的,正如 Blagovest 在他的评论中指出的那样。使用进程替换(这是
<<(commands)
语法)将所有内容保持在同一进程中,因此可以更改全局变量。顺便说一句,您的管道也可以得到改进,
减少一次需要担心的
grep
调用。The problem is the pipe, not the loop. Try it this way
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
One less invocation of
grep
to worry about.这在某种程度上绕过了您的问题(这是一个好问题),但是您可以简单地使用以下方法获得相同的结果:
($(cmd))
构造使用命令的输出初始化 bash 数组之内。您可以使用
${#_constr[*]}
获取元素的数量。This somewhat by-passes your question (and it's a good question), but you can achieve the same results using simply:
The
($(cmd))
construct initialises a bash array using the output of the command within.and you can get the number of elements using
${#_constr[*]}
.或者,您可以在子 shell 内移动 echo 语句:
请注意插入括号以显式定义子 shell 的开始和结束位置。
Alternatively, you can move the echo statements inside the subshell:
Note the insertion of the parenthesis to explicitly define where the subshell begins and ends.