title: Variables value gets lost in subshell
body: <p>This bash script concatenates the names for jar files to a classpath (variable CP), in the while loop the value is correct but is lost in the subshell as descibed in this related question <a href="https://stackoverflow.com/questions/124167/bash-variable-scope">Bash variable scope</a></p>
  
  <pre><code>#!/bin/bash
  CP="AAA"
  func() {
          ls -1 | while read JAR
          do
                  if [ ! -z "$CP" ]; then
                          CP=${CP}':'
                  fi
                  CP=${CP}${JAR}
          done
          echo $CP # &lt;-- prints AAA
  }
  
  func
  </code></pre>
  
  <p>My question is, since I can't figure out which element will be the last one, how can the value be saved.</p>
  
  <p>Do I actually have to save the current value (repeatedly in the loop) to a file?</p>
  
  <p>EDIT:</p>
  
  <p>A colleague came up with this command sequence which works well</p>
  
  <pre><code>ls | xargs echo|tr ' ' :
  </code></pre>