EN
Bash - create local variable in function
0 points
In this article, we would like to show you how to create local variable in function using Bash.
Quick solution:
xxxxxxxxxx
1
my_function() {
2
local variable_name # local variable
3
}
Hint: it is possible to create and initialize variable by using
local variable_name="Some value here..."
.
In this example, we use local
keyword to create a local variable inside a function.
When we increment and print the function inside the for loop within the function, it works fine. However, when we try to use it outside the function, it can't be found since it's outside the scope.
xxxxxxxxxx
1
2
3
my_function() {
4
local i # local variable
5
6
for i in 1 2 3; do
7
echo "inside function: i = $i"
8
done
9
}
10
11
my_function
12
13
echo "outside function: i = $i"