Bash script variable placement
So does Bash first run through the whole script to find variables?
Nope. As you yourself discovered in your example, Bash scripts are executed from top to bottom.
A good practice is to define all variables that you need at the top of your script.
That's a very sloppy way of saying that the shell scans each command for expansions, such as for example variables (but also command substitutions etc.)
The text could be interpreted to imply that the shell reads the whole script and looks for variables on every line before execution. That is not so. It processes the script command by command, not line by line. A command could span several lines. A command is not processed until the shell interpreter gets to it in its execution of the script.
The bash
shell does the following with each command before executing it:
- brace expansion
- tilde expansion
- parameter and variable expansion
- arithmetic expansion
- command substitution (done in a left-to-right fashion)
- word splitting
- pathname expansion
- quote removal