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 $iafter the loop shows that it's not a loop-local variable. If you setito a value before the loop, it will be overwritten. – berndbausch Jun 01 '21 at 08:04for i in $directoriesiszshsyntax, notbashsyntax. Inbash(like inkshwhose array syntaxbashcopied; it would also work inzsh), you'd needfor i in "${directories[@]}"to loop over all the elements of the$directoriesarray. – Stéphane Chazelas Jun 02 '21 at 12:52directoriesis 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