1

I have a really stupid question, but I would just want to confirm. I have internally tested it as well with the following code.

for x in ${!test_array[@]} 
do
    echo hey
done

So my question is, apparently the for loop will simply ignore anything between doing and done if the array is empty. I have tested it, and if the array is empty, echo hey will never be run, which means the script will never bother doing anything within do .. and done. If the array has at least one element, then it will run echo hey.

I just want to confirm if my understanding is correct. I mean from my testing it definitely seems to be that way.

terdon
  • 242,166
  • 1
    you should use "${!test_array[@]}" with quotes there. See https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters and you can thank us later. – ilkkachu May 27 '22 at 15:41
  • OH yes, my mistake. i did in my script but I forgot it when I post it here. – yoloyolo May 27 '22 at 16:00
  • this (valid code) is what the shell sees: for x in ; do echo hey; done -- "what the shell sees" after parameter expansion – glenn jackman May 27 '22 at 16:46

2 Answers2

1

Your understanding is correct. A for loop will execute the code between do and done for every item in words. If there are no items in words then there is nothing to loop.

However if you omit in words altogether it will loop over the positional parameters.

For example

$ set -- one two
$ for f; do echo $f; done
one
two

See 3.2.5.1 Looping Constructs

jesse_b
  • 37,005
1

Yes, that is correct. Think about it this way: if you are at a children's party and I tell you that every child with a blue shirt should be given a cookie, then if there are no children wearing blue, you won't ever open the cookie jar.

Here, you are telling the shell to do something to every element of the array and since there are no elements, it won't even enter the loop.

terdon
  • 242,166