Recall & Review
beginner
What is a local variable in bash scripting?
A local variable is a variable declared inside a function using the 'local' keyword. It exists only within that function and is not accessible outside it.
Click to reveal answer
beginner
How do you declare a local variable inside a bash function?
Use the 'local' keyword before the variable name, like this:
local varname=value.Click to reveal answer
beginner
Why use local variables inside bash functions?
Local variables prevent conflicts by keeping variables inside functions separate from variables outside. This helps avoid accidental changes to global variables.
Click to reveal answer
intermediate
What happens if you don't use 'local' inside a bash function?
Variables declared without 'local' inside a function are global. They can change values outside the function, which might cause unexpected results.
Click to reveal answer
beginner
Example: What is the output of this script?
myfunc() {
local x=5
echo $x
}
myfunc
echo $xOutput:
5
(empty line)
Explanation: Inside the function, 'x' is local and prints 5. Outside, 'x' is not set, so echo prints nothing.
Click to reveal answer
What keyword is used to declare a local variable inside a bash function?
✗ Incorrect
The 'local' keyword declares a variable that exists only inside the function.
If a variable is declared inside a function without 'local', what is its scope?
✗ Incorrect
Without 'local', variables inside functions are global and affect the whole script.
Why is it good practice to use local variables in bash functions?
✗ Incorrect
Local variables keep function variables separate, avoiding conflicts with global variables.
What will this script print?
func() {
local a=10
echo $a
}
func
echo $a✗ Incorrect
Inside the function, 'a' is 10. Outside, 'a' is not set, so echo prints nothing.
Which of these is true about local variables in bash?
✗ Incorrect
Local variables exist only while the function runs and disappear after it finishes.
Explain what a local variable is in bash and why you would use the 'local' keyword inside a function.
Think about how variables inside functions can affect the rest of the script.
You got /4 concepts.
Describe what happens if you declare a variable inside a bash function without using 'local'. How does it affect the script?
Consider the difference in variable scope with and without 'local'.
You got /4 concepts.