0
0
Bash Scriptingscripting~20 mins

Local variables (local keyword) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Local Variable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output of this Bash script using local variables?
Consider the following Bash script. What will it print when run?
Bash Scripting
my_func() {
  local var="inside"
  echo "$var"
}
var="outside"
my_func
echo "$var"
Ainside\noutside
Binside\ninside
Coutside\noutside
Doutside\ninside
Attempts:
2 left
💡 Hint
Think about how the local keyword limits the variable scope inside the function.
💻 Command Output
intermediate
2:00remaining
What error or output does this script produce?
What happens when you run this Bash script?
Bash Scripting
func() {
  local x=5
  ((x++))
  echo $x
}
func
echo $x
A6\n\n
B6\n
C6\n5
DSyntax error
Attempts:
2 left
💡 Hint
Remember local variables do not affect global variables.
📝 Syntax
advanced
1:30remaining
Which option correctly declares a local variable with initial value in Bash?
Choose the correct syntax to declare a local variable named 'count' with value 10 inside a function.
Alocal count 10
Blocal count=10
Clocal count := 10
Dlocal count == 10
Attempts:
2 left
💡 Hint
Bash uses = to assign values, no spaces around =.
🔧 Debug
advanced
2:00remaining
Why does this script print 'local' twice instead of 'local' and 'global'?
Examine the script below and find why the output is not as expected.
Bash Scripting
var="global"
func() {
  var="local"
  echo "$var"
}
func
echo "$var"
ABecause the function is not called properly.
BBecause 'var' is always global in Bash, local keyword is ignored.
CBecause 'var' inside func is not declared local, it overwrites the global variable.
DBecause echo cannot print local variables.
Attempts:
2 left
💡 Hint
Think about variable scope and the effect of missing 'local'.
🚀 Application
expert
2:30remaining
How many variables are accessible outside after running this script?
Given the script below, how many variables named 'a', 'b', and 'c' exist and are accessible outside the function?
Bash Scripting
a=1
func() {
  local a=2
  b=3
  local c=4
}
func
echo "$a $b $c"
ANo variables accessible globally
B3 variables: 'a', 'b', and 'c' all accessible globally
C1 variable: only 'a' accessible globally
D2 variables: 'a' and 'b' accessible; 'c' is local and not accessible
Attempts:
2 left
💡 Hint
Local variables exist only inside functions; others affect global scope.