Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Propagate value of variable to outside of the loop [duplicate]

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?

like image 862
masuch Avatar asked Sep 12 '11 15:09

masuch


1 Answers

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.

like image 133
sorpigal Avatar answered Sep 29 '22 16:09

sorpigal