Functions in Bash
Posted on Dec 04, 2019 in Computer Science
Things under legendu.net/outdated are outdated technologies that the author does not plan to update any more. Please look for better alternatives.
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: "$x
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: "$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.
%%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.
%%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.
%%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
%%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