0
0
Bash Scriptingscripting~30 mins

Recursive functions in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Recursive Functions in Bash
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use echo "Factorial of $num is $result" to print the message.