Exercise: Variable Scope
Explore how to manage variable scope within Bash functions by working through an exercise that demonstrates local variables and their visibility across function calls. Learn why variables behave differently inside and outside functions and how this affects your scripts' output.
We'll cover the following...
We'll cover the following...
Exercise
What text does the script in quiz-variable-scope.sh print to the console when it executes?
#!/bin/bash
bar()
{
echo "bar1: var = $var"
var="bar_value"
echo "bar2: var = $var"
}
foo()
{
local var="foo_value"
echo "foo1: var = $var"
bar
echo "foo2: var = $var"
}
echo "main1: var = $var"
foo
echo "main2: var = $var"
Output explanation
The quiz-variable-scope.sh script prints the following text:
main1: var =
foo1: var ...