4

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 ?

msouth
  • 135
  • 1
  • 7
von spotz
  • 435
  • 5
    And what happened when you tried it? – choroba Jun 01 '21 at 07:10
  • @choroba I want to know if I must define counter-variables as local and if I must be careful with choosing their names because of possible conflicts with other global variables. What's the problem here? – von spotz Jun 01 '21 at 07:56
  • 3
    An echo $i after the loop shows that it's not a loop-local variable. If you set i to a value before the loop, it will be overwritten. – berndbausch Jun 01 '21 at 08:04
  • 2
    choroba's point was that it's easy to answer the question for yourself by doing an experiment. – Peter Cordes Jun 01 '21 at 19:44
  • 3
    @PeterCordes, it's very easy to do an experiment and learn the wrong thing from it. Much more helpful is understanding of what behavior was intended / should be. Thus this question. It is especially easy to see where this question is coming from since it's often difficult to read and understand the bash manual when you do not already have an understanding of what it's saying. – James Caccese Jun 02 '21 at 02:58
  • 1
    Let's close down StackExchange and do it all by ourselves by experiments and testing suites ! Btw: "can anyone help me with this rspec problem... ?" – von spotz Jun 02 '21 at 05:43
  • 1
    In any case for i in $directories is zsh syntax, not bash syntax. In bash (like in ksh whose array syntax bash copied; it would also work in zsh), you'd need for i in "${directories[@]}" to loop over all the elements of the $directories array. – Stéphane Chazelas Jun 02 '21 at 12:52
  • Stephane: While your comment is correct about arrays, there's no indication in the question that directories is an array. And in fact, it's quite common for such lists to simply be whitespace-separated lists (however much that hurts our structured-data-loving souls), in which case the syntax is correct. – Ti Strga May 29 '22 at 20:05

1 Answers1

19

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).

Stephen Kitt
  • 434,908