global and local variables
By default, every variable in bash is global to every function, script and even the outside shell if you are declaring your variables inside a script.
If you want your variable to be local to a function, you can use local to have that variable a new variable that is independent to the global scope and whose value will only be accessible inside that function.
Global variables
Section titled “Global variables”var="hello"
function foo(){ echo $var}
fooWill obviously output “hello”, but this works the other way around too:
function foo() { var="hello"}
fooecho $varWill also output "hello"
Local variables
Section titled “Local variables”function foo() { local var var="hello"}
fooecho $varWill output nothing, as var is a variable local to the function foo, and its value is not visible from outside of it.
Mixing the two together
Section titled “Mixing the two together”var="hello"
function foo(){ local var="sup?" echo "inside function, var=$var"}
fooecho "outside function, var=$var"Will output
inside function, var=sup?outside function, var=hello