By default, variables defined in a function are global, i.e., they are visible outside the function too.
In [12]:
%%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: "$x
Declaring a variable as local
make it visible only in the function.
In [11]:
%%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: "$x
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.
In [13]:
%%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: "$x
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.
In [14]:
%%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: "$x
By default, loop variables are global. However, you can declare them as local before using them.
In [17]:
%%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: "$i
In [19]:
%%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: "$i
In [ ]: