0
0
Bash Scriptingscripting~5 mins

Recursive functions in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ATo print the function name
BTo start the recursion
CTo stop the recursion and prevent infinite calls
DTo call another script
In bash, how do you call a function named 'factorial' with argument 5?
Acall factorial(5)
Bfactorial 5
Cfactorial(5)
Drun factorial 5
What will happen if a recursive bash function never reaches its base case?
AIt will print the base case automatically
BIt will skip recursion
CIt will return zero immediately
DIt will run forever until the system stops it
Which of these is a valid base case for a countdown function in bash?
Aif [ $1 -le 0 ]; then echo "Done"; fi
Bif [ $1 -gt 0 ]; then echo "Done"; fi
Cif [ $1 -eq 10 ]; then echo "Done"; fi
Dif [ $1 -lt 0 ]; then echo "Start"; fi
What does this line do in a recursive bash function? countdown $(( $1 - 1 ))
ACalls countdown with the argument decreased by 1
BEnds the function
CPrints the current argument
DIncreases the argument by 1
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.