Let’s talk about variable scope. Scope refers to which part of a script, a variable is visible. 1
In Bash 2
all variables are by default global, and that means that they are visible everywhere 3
inside the script. I'm creating a new script. 4
So I'm defining a variable called var1 =" AA" and var2="BB" and the function: function 5
func1 6
And I want to see the values of the variables inside the function, so echo "Inside func1: var1= 7
$var1, var2=$var2 " and I'm calling it so func1 8
I'm running the script and we see that the variables are global; they are visible inside the function. 9
Let's see what happens if a global variable is changed inside the function. 10
So var1="XX" 11
And after calling the function, I want to check the value of var1. 12
So "After calling func1." 13
And we see that the variable was changed and the change is seen outside the function as well. 14
If you want to declare a local variable within the function body, use the local keyword, which can be 15
used only inside functions. 16
Let's make var2 local inside the function. 17
So local var2= "YY" 18
I'm saving and running the script. 19
And we see that var2 is local to the function, and its new value is available only within the function 20
body. 21
Outside the function var2 is global and has the initial value; the function didn't change or worked 22
on the global variable var2. It is generally considered good practice to use local variables within 23
functions in order to keep everything contained within the function.