On Mon, Dec 23, 2013 at 11:57:32PM +0100, rens wrote: > ls -1 /usr/bin|head -10 |while read fname > do > cval=$(( cval +1 )) > echo cval = $cval file = $fname > done > # one would think cval is now 10. but it is not, contrary to any other > programming language........ > > echo " after while: cval = $cval" > _______________________________ > > does not set the value of cval after exiting the while loop.
The pipe creates subshells, so your entire while loop is running in a subshell (a child process). Changes to variables inside the loop will not persist once the subshell terminates. http://mywiki.wooledge.org/BashFAQ/024 explains the issue in more detail, and provides alternatives. I'm sorry that other people did not explain the issue usefully.