It is the pipeline that is the cause for spawning the sub-shell:
Code:
#!/bin/sh
VAR=Old
pgrep sh | wc -l
echo Entering the loop
# echo A | while read REPLY; do
while read REPLY; do
echo Here
VAR=New
echo "Inside while ... done loop: VAR = $VAR"
pgrep sh | wc -l
if [ "X$REPLY" = X"Q" ] ; then
break
fi
done
echo Back to main program: VAR = $VAR
pgrep sh | wc -l
Running it:
Code:
$ ./test2.sh
9
Entering the loop
a
Here
Inside while ... done loop: VAR = New
9
a
Here
Inside while ... done loop: VAR = New
9
Q
Here
Inside while ... done loop: VAR = New
9
Back to main program: VAR = New
9
So no change in the number of shells here and the variable now has been modified as expected.