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:

  1. brace expansion
  2. tilde expansion
  3. parameter and variable expansion
  4. arithmetic expansion
  5. command substitution (done in a left-to-right fashion)
  6. word splitting
  7. pathname expansion
  8. quote removal

Tags:

Bash