I think I can explain why it is happening, but I'm not sure how to work around it...

A Bash script is a sequential list of commands, executed one after the other (very oversimplified, but go with...