Local and global variables
When it comes to declaring any variable in a script—or for that matter, anywhere at all—one crucial attribute for that variable is its scope. By scope, we mean where the variable has the value we declared. Scope is very important since not understanding how it works means that we can get unexpected results in some cases.
Getting ready
Defining a global scope to our variables is something bash
does by default, without any interaction with us. All variables that are defined are global variables; their value is the same in the entire script. If we change the variable value by reassigning it (remember that operations on the value do not change the value itself), this value changes globally, and the old value is lost.
There is another thing we can do when declaring variables, and that is to declare them locally. In simple terms, this means that we are explicitly telling bash
that we will use this variable in some limited part of the code...