7.3.6.4. Scope of variables

The scope of a variable is the parts of the script that can see the variable. In bash the default scope is global, which means that all variables are visible anywhere in the script. In the context of functions, a variable defined in the script is available and changeable in a function:

change_var () {
    var="$var is changed in the function."
}

var="Variable 1"
echo $var
change_var
echo $var

prints:

Variable 1
Variable 1 is changed in the function.

This can be dangerous, because variables can be inadvertently modified by a function. It is considered good practice to declare the function variables local to the function:

change_var () {
    local var="$var is changed in the function."
    echo "In the function: $var"
}

var="Variable 1"
echo $var
change_var
echo $var

will print:

Variable 1
In the function: Variable 1 is changed in the function.
Variable 1

The variable “var” in the function is local and cannot change the global variable with the same name in the main script. However, as shown, it can use the variable from the main script.