shell programming: “for” loops vs. “while” loops and scope of variables created within loop bodies

Variables, that you create (by assignment) within loop bodies, are well visible outside the loop body. This is valid for both kinds of loop.

CAVEAT:
If the “while” loop reads from a pipe, the “while” loop is executed within a subshell, i.e. the scope of the variables within the loop ends with the loop.
Example:

x=a
echo hello |
while read l
do
  x=b
done
echo “x=$x”

What’s the output of this echo?

x=a

Example:

x=a
for l in hello
do
  x=b
done
echo “x=$x”


What’s the output of this echo?

x=b


Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.