This is not completely wrong but also not completely right:
"UNIX" is completely indifferent about this topic. This is a property of the shell and hence the behavior you see depends on which shell you use (and how you configure it).
Most of todays shells have a common ancestor, the "Bourne Shell", which indeed shows the behavior you noticed. In the following sample:
process | while read line ; do
var=<something>
done
the while-do..done-loop is the second part of a pipeline and therefore executed in a subshell. Therefore, whatever value you assign to "var", it will be lost outside the loop because after the loop the subshell is simply closed. Notice that defining it up front like this:
var=<value>
process | while read line ; do
var=<something>
done
will not help: the variable "var" in the subshell may have the same name as the variable "var" in the script shell but they are not the same at all. The only way you can overcome this is by replacing the pipeline with a redirection:
while read line ; do
var=<something>
done < $(process)
Today, the real Bourne Shell is rarely used at all (IIRC it is from the beginning of the eighties) but mostly one of its two main successors: Korn Shell (ksh) and the Bourne Again Shell (bash). Both are (almost) completely backwards compatible with the Bourne Shell which means every shell script written for Bourne Shell should run on Korn shell as well as bash.
In ksh this (rather unintuitive, IMHO) behavior of the Bourne Shell was abandoned and therefore the two examples above work absolutely identical.
i=1
while [ i -le 100 ] ; do
(( i += 1 ))
done
print $i
This will produce "100" as output in ksh and not "1", like in the Bourne Shell.
In bash, however, the original behavior of the Bourne Shell was retained and hence would produce "1" too. But because that was unintuitive even for the bash programmers in bash 4 (? i am not sure about the exact version) the shell-option "lastpipe" was introduced. If you set that with
shopt -s lastpipe
bash will work exactly like ksh (in this regard). Notice, though, that you might still come across bash versions which will not understand this configuration. You will have to do it either this way (redirection):
totalstr=""
while IFS= read -r line ; do
totalstr=$totalstr,$line;
done < $(echo "$loc")
echo "Final Output:$totalstr"
or you can do it this way (a so-called "here-document"):
totalstr=""
while IFS= read -r line ; do
totalstr=$totalstr,$line;
done <<- EOF
echo "$loc"
EOF
echo "Final Output:$totalstr"
I hope this helps.
bakunin