I have had this issue before and can confirm this can be a problem. In my case, a regression script first executes a git pull and might get updated after it starts to run, causing issues.
The problem is usually when the shell will go back and checks if there are any more lines to interpret. This can cause error even when the desired code is within a loop. To avoid this, use the structure in this postthis post.