title: While-loop subshell dilemma in Bash
body: <p>i want to compute all *bin files inside a given directory. Initially I was working with a <code>for-loop</code>:</p>
  
  <pre><code>var=0
  for i in *ls *bin
  do
     perform computations on $i ....
     var+=1
  done
  echo $var
  </code></pre>
  
  <p>However, in some directories there are too many files resulting in an error: <code>Argument list too long</code></p>
  
  <p>Therefore, I was trying it with a piped <code>while-loop</code>:</p>
  
  <pre><code>var=0
  ls *.bin | while read i;
  do
    perform computations on $i
    var+=1
  done
  echo $var
  </code></pre>
  
  <p>The problem now is by using the pipe subshells are created. Thus, <code>echo $var</code> returns <code>0</code>.<br>
  How can I deal with this problem?<br>
  The original Code:</p>
  
  <pre><code>#!/bin/bash
  
  function entropyImpl {
      if [[ -n "$1" ]]
      then
          if [[ -e "$1" ]]
          then
              echo "scale = 4; $(gzip -c ${1} | wc -c) / $(cat ${1} | wc -c)" | bc
          else
              echo "file ($1) not found"
          fi
      else
          datafile="$(mktemp entropy.XXXXX)"
          cat - &gt; "$datafile"
          entropy "$datafile"
          rm "$datafile"
      fi
  
      return 1
  }
  declare acc_entropy=0
  declare count=0
  
  ls *.bin | while read i ;
  do  
      echo "Computing $i"  | tee -a entropy.txt
      curr_entropy=`entropyImpl $i`
      curr_entropy=`echo $curr_entropy | bc`  
      echo -e "\tEntropy: $curr_entropy"  | tee -a entropy.txt
      acc_entropy=`echo $acc_entropy + $curr_entropy | bc`
      let count+=1
  done
  
  echo "Out of function: $count | $acc_entropy"
  acc_entropy=`echo "scale=4; $acc_entropy / $count" | bc`
  
  echo -e "===================================================\n" | tee -a entropy.txt
  echo -e "Accumulated Entropy:\t$acc_entropy ($count files processed)\n" | tee -a entropy.txt
  </code></pre>