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[@]} 
    echo hey

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.

  • 1
    you should use "${!test_array[@]}" with quotes there. See unix.stackexchange.com/questions/131766/… and you can thank us later.
    – ilkkachu
    May 27 at 15:41
  • OH yes, my mistake. i did in my script but I forgot it when I post it here.
    – yoloyolo
    May 27 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 May 27 at 16:46

2 Answers 2


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

See Looping Constructs


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.

  • Thanks so much , this is really clear example. thanks
    – yoloyolo
    May 27 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.