8

in the idiom

for i in $directories; do
  # ...
done

... is the variable $i local or global?

And what if there happens to be a global variable of the same name. Does bash work with the global variable or the one of the for ... in ... header ?

0

1 Answer 1

23

for doesn’t introduce its own variable scope, so i is whatever it is on entry to the for loop. This could be global, or local to whatever function declared it as local, or even global but in a sub-shell.

On exit from the for loop, the variable will have the last value it had in the loop, unless it ended up in a sub-shell. How much that affects depends on the variable’s scope, so it is a good idea to declare loop variables as local inside functions (unless the side-effect is desired).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.