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?
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.
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'
One less invocation of grep
to worry about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With