Things under legendu
Fish Shell is preferred to Bash/Zsh. The following content is for Bash/Zsh only.
By default, variables defined in a function are global, i.e., they are visible outside the function too.
%%bash
function my_fun(){
x=1
x=2
echo "Value of x inside the function: "$x
}
my_fun
echo "Value of x outside the function: "$xValue of x inside the function: 2
Value of x outside the function: 2
Declaring a variable as local make it visible only in the function.
%%bash
function my_fun(){
local x=1
x=2
echo "Value of x inside the function: "$x
}
my_fun
echo "Value of x outside the function: "$xValue of x inside the function: 2
Value of x outside the function:
You can declare a variable as local multiple times (which is different from other programming languages),
but of course,
only the first local declaration of a variable is necessary
and the following local declaration of the same variable are useless and redundant.
%%bash
function my_fun(){
local x=1
local x=2
echo "Value of x inside the function: "$x
}
my_fun
echo "Value of x outside the function: "$xValue of x inside the function: 2
Value of x outside the function:
If you have a global variable in a function
and then declare it as local.
The last value before it is declared as local is still visible outside the function.
%%bash
function my_fun(){
x=1
local x=2
echo "Value of x inside the function: "$x
}
my_fun
echo "Value of x outside the function: "$xValue of x inside the function: 2
Value of x outside the function: 1
By default, loop variables are global. However, you can declare them as local before using them.
%%bash
function my_fun(){
for i in {1..3}; do
echo $i
done
echo "Value of i inside the function: "$i
}
my_fun
echo "Value of i outside the function: "$i1
2
3
Value of i inside the function: 3
Value of i outside the function: 3
%%bash
function my_fun(){
local i
for i in {1..3}; do
echo $i
done
echo "Value of i inside the function: "$i
}
my_fun
echo "Value of i outside the function: "$i1
2
3
Value of i inside the function: 3
Value of i outside the function: