Bash script variable placement

bash

I started to learn Bash scripting and I'm using Bash scripting tutorial

There it says

Before Bash interprets (or runs) every line of our script it first checks to see if any variable names are present. For every variable it has identified, it replaces the variable name with its value. Then it runs that line of code and begins the process again on the next line.

So does Bash first run through the whole script to find variables? I'm not sure whether this is what the author tried to say but if yes I guess it is not correct?

when I execute:

#!/bin/bash


echo "hello $USERR"



USERR=John

I get helloas result.

If I run:

#!/bin/bash


USERR=John

echo "hello $USERR"

then i get hello John as result.

Best Answer

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.

Related Question