Recall & Review
beginner
What is a recursive function in bash scripting?
A recursive function is a function that calls itself to solve smaller parts of a problem until it reaches a base case to stop.
Click to reveal answer
beginner
Why do recursive functions need a base case?
The base case stops the recursion by providing a condition where the function no longer calls itself, preventing infinite loops.
Click to reveal answer
beginner
How do you define a recursive function in bash?
You define a function normally and inside it, call the same function with a changed argument to approach the base case.
Click to reveal answer
beginner
Example: What does this bash recursive function do?
function countdown() {
if [ $1 -le 0 ]; then
echo "Done!"
else
echo "$1"
countdown $(( $1 - 1 ))
fi
}This function counts down from the given number to zero, printing each number, then prints "Done!" when it reaches zero.
Click to reveal answer
intermediate
What happens if a recursive function in bash has no base case?
The function will call itself endlessly, causing the script to crash or run out of memory (stack overflow).
Click to reveal answer
What is the purpose of the base case in a recursive bash function?
✗ Incorrect
The base case stops the recursion by providing a condition where the function no longer calls itself.
In bash, how do you call a function named 'factorial' with argument 5?
✗ Incorrect
In bash, you call a function by writing its name followed by arguments separated by spaces.
What will happen if a recursive bash function never reaches its base case?
✗ Incorrect
Without a base case, recursion never stops and the function calls itself endlessly.
Which of these is a valid base case for a countdown function in bash?
✗ Incorrect
The base case stops recursion when the number is zero or less.
What does this line do in a recursive bash function?
countdown $(( $1 - 1 ))
✗ Incorrect
It calls the function again with the argument reduced by one to approach the base case.
Explain how a recursive function works in bash and why a base case is important.
Think about how you solve a big problem by breaking it into smaller ones.
You got /3 concepts.
Write a simple recursive bash function that counts down from a number to zero and prints "Done!" at the end.
Use if to check if number is zero or less, else call function again with smaller number.
You got /4 concepts.