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:
my_function() {
local variable_name # local variable
}
Hint: it is possible to create and initialize variable by using
local variable_name="Some value here...".
Practical example
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.
#!/bin/bash
my_function() {
local i # local variable
for i in 1 2 3; do
echo "inside function: i = $i"
done
}
my_function
echo "outside function: i = $i"