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 ?
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).
echo $i
after the loop shows that it's not a loop-local variable. If you seti
to a value before the loop, it will be overwritten. – berndbausch Jun 01 '21 at 08:04for i in $directories
iszsh
syntax, notbash
syntax. Inbash
(like inksh
whose array syntaxbash
copied; it would also work inzsh
), you'd needfor i in "${directories[@]}"
to loop over all the elements of the$directories
array. – Stéphane Chazelas Jun 02 '21 at 12:52directories
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