0
0
Bash Scriptingscripting~20 mins

Return values (return and echo) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Return Mastery Badge
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 function call?
Consider the following Bash script. What will be printed when the function is called?
Bash Scripting
myfunc() {
  echo "Hello"
  return 5
}
myfunc
echo $?  # prints the return value of the function
AHello\n5
B5\nHello
CHello
D5
Attempts:
2 left
💡 Hint
Remember that echo prints to standard output, and return sets the exit status.
💻 Command Output
intermediate
2:00remaining
What does this script output?
What is the output of this Bash script?
Bash Scripting
func() {
  local val=10
  echo $val
  return 3
}
result=$(func)
echo "$result"
echo $?  # exit status of func
A3\n10
B10\n3
C10\n0
D3\n0
Attempts:
2 left
💡 Hint
Check what is captured by command substitution and what is the exit status.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in a Bash function?
Which of these function definitions will cause a syntax error?
Amyfunc() { echo "Hi"; return 1; }
Bmyfunc() { echo "Hi"; return 1 }
C} ;1 nruter ;"iH" ohce { )(cnufym
Dmyfunc() { echo "Hi" return 1; }
Attempts:
2 left
💡 Hint
Look for missing semicolons or command separators.
🚀 Application
advanced
2:00remaining
How to capture both output and return code from a Bash function?
You want to capture the output of a Bash function and also check its return code. Which snippet does this correctly?
A
output=$(myfunc; ret=$?)
echo "$output"
echo $ret
B
ret=$(myfunc)
output=$?
echo "$output"
echo $ret
C
output=$(myfunc)
ret=$?
echo "$output"
echo $ret
D
output=myfunc
ret=$?
echo "$output"
echo $ret
Attempts:
2 left
💡 Hint
Remember that $? holds the exit status of the last command.
🧠 Conceptual
expert
2:00remaining
What is the difference between return and echo in Bash functions?
Which statement best describes the difference between return and echo in Bash functions?
A"return" sets the function's exit status, "echo" prints text to standard output.
B"return" sends a value to the caller as output, "echo" sets the function's exit status.
C"return" prints text to standard output, "echo" sets the function's exit status.
D"return" and "echo" both print text but differ in syntax.
Attempts:
2 left
💡 Hint
Think about what return and echo do in a shell script.