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 re
None of these answers seem to get into actually returning the value properly, echoing out the answer is fine with a very simple routine, but say you want output of the script in action, this is useless. I don't have the best answer but I don't have much time to figure it out either, so I'm just going to suggest to output exactly what you want to a temp file and read that (surprised it hasn't been mentioned to date) :
#!/bin/bash
CP="AAA"
func() {
ls -1 | (
while read JAR
do
if [ ! -z "$CP" ]; then
CP=${CP}':'
fi
CP=${CP}${JAR}
done
echo "$CP" > /tmp/cp-value-file
)
}
func
CP=$(cat /tmp/cp-value-file)
echo $CP
Downside: will in some cases need to write to the disk every iteration of the loop.