📖 Scenario: You are helping a friend who wants to understand how to use recursion in Bash scripts. Recursion is when a function calls itself to solve smaller parts of a problem. This is useful for tasks like calculating factorials.
🎯 Goal: Build a Bash script that uses a recursive function to calculate the factorial of a given number.
📋 What You'll Learn
Create a Bash function named factorial that calculates factorial recursively
Use a base case to stop recursion when the input is 1
Call the factorial function with a number stored in a variable num
Print the factorial result
💡 Why This Matters
🌍 Real World
Recursive functions help solve problems that can be broken down into smaller similar problems, like file system traversal or mathematical calculations.
💼 Career
Understanding recursion in scripting is useful for automation tasks, system administration, and writing efficient scripts that handle complex data.
Progress0 / 4 steps
1
Set the number to calculate factorial
Create a variable called num and set it to 5.
Bash Scripting
Hint
Use num=5 to set the variable.
2
Write the recursive factorial function
Write a Bash function named factorial that takes one argument n. Use an if statement to check if n is 1. If yes, return 1. Otherwise, return n multiplied by the factorial of n-1.
Bash Scripting
Hint
Use if [ "$n" -eq 1 ] for the base case and call factorial $((n - 1)) recursively.
3
Call the factorial function with the number
Call the factorial function with the variable num and save the result in a variable called result.
Bash Scripting
Hint
Use result=$(factorial "$num") to capture the output.
4
Print the factorial result
Print the text Factorial of 5 is followed by the value of result using echo.
Bash Scripting
Hint
Use echo "Factorial of $num is $result" to print the message.
Practice
(1/5)
1. What is the main purpose of a base case in a recursive Bash function?
easy
A. To increase the input value for the next call
B. To call the function again with the same input
C. To print the current value of a variable
D. To stop the recursion and prevent infinite loops
Solution
Step 1: Understand recursion basics
A recursive function calls itself repeatedly with smaller inputs.
Step 2: Role of base case
The base case stops the recursion to avoid infinite loops and eventual crash.
Final Answer:
To stop the recursion and prevent infinite loops -> Option D
Quick Check:
Base case = stop recursion [OK]
Hint: Base case always stops recursion to avoid endless calls [OK]
Common Mistakes:
Forgetting the base case causes infinite recursion
Using base case to increase input instead of stopping
Confusing base case with recursive step
2. Which of the following is the correct syntax to define a recursive function named countdown in Bash?
easy
A. countdown() { while [ $1 -gt 0 ]; do echo $1; (( $1-- )); done; echo Done; }
B. def countdown(n): if n <= 0: print('Done') else: print(n) countdown(n-1)
C. function countdown() { if [[ $1 -le 0 ]]; then echo Done; else echo $1; countdown $(( $1 - 1 )); fi }
D. function countdown { echo $1; countdown $(( $1 - 1 )); }
Solution
Step 1: Identify Bash function syntax
Bash functions use the syntax: function name() { commands; } or name() { commands; }.
Step 2: Check recursive call and base case
function countdown() { if [[ $1 -le 0 ]]; then echo Done; else echo $1; countdown $(( $1 - 1 )); fi } correctly defines a function with a base case (if $1 <= 0) and recursive call countdown $(( $1 - 1 )).
Final Answer:
function countdown() { if [[ $1 -le 0 ]]; then echo Done; else echo $1; countdown $(( $1 - 1 )); fi } -> Option C
Quick Check:
Bash recursion syntax = function countdown() { if [[ $1 -le 0 ]]; then echo Done; else echo $1; countdown $(( $1 - 1 )); fi } [OK]
Hint: Look for Bash syntax with base case and recursive call [OK]
Common Mistakes:
Using Python syntax in Bash function
Missing base case causing infinite recursion
Incorrect function declaration without parentheses
3. What will be the output of this Bash script?
factorial() {
if [[ $1 -le 1 ]]; then
echo 1
else
local prev=$(factorial $(( $1 - 1 )))
echo $(( $1 * prev ))
fi
}
factorial 3
medium
A. 1
B. 6
C. 3
D. 9
Solution
Step 1: Understand factorial recursion
factorial(3) calls factorial(2), which calls factorial(1). factorial(1) returns 1.
Assuming echo returns a number usable in arithmetic
Ignoring base case correctness
Thinking function name 'sum' is reserved
5. You want to write a recursive Bash function list_files that prints all files in a directory and its subdirectories. Which approach correctly handles recursion and avoids infinite loops?
hard
A. Check if the argument is a directory; if yes, list files and call list_files on each subdirectory; else print the file name
B. Call list_files on the directory without checking type, then print the directory name
C. Use a loop to list files only in the current directory without recursion
D. Call list_files on all files and directories without base case
Solution
Step 1: Understand recursive directory traversal
To list files recursively, check if the argument is a directory; if so, process contents recursively.
Step 2: Avoid infinite loops by checking file type
Only recurse into directories; print file names directly to avoid infinite recursion.
Final Answer:
Check if the argument is a directory; if yes, list files and call list_files on each subdirectory; else print the file name -> Option A