Introduction
Recursive functions help solve problems by calling themselves with smaller parts until they reach a simple case. This makes some tasks easier to write and understand.
# Define a recursive function function function_name() { # Base case: stop condition if [ condition ]; then return fi # Recursive case: call the function again with changed input function_name new_input } # Call the function function_name initial_input
# Example: countdown from a number to 1 function countdown() { if [ $1 -le 0 ]; then echo "Done!" return fi echo "$1" countdown $(( $1 - 1 )) } countdown 3
# Edge case: countdown from 0 countdown 0
# Edge case: countdown from 1 countdown 1
#!/bin/bash # Recursive function to calculate factorial function factorial() { if [ $1 -le 1 ]; then echo 1 return fi local previous_factorial=$(factorial $(( $1 - 1 ))) echo $(( $1 * previous_factorial )) } # Print factorial of 5 number=5 result=$(factorial $number) echo "Factorial of $number is $result"
countdown in Bash?factorial() {
if [[ $1 -le 1 ]]; then
echo 1
else
local prev=$(factorial $(( $1 - 1 )))
echo $(( $1 * prev ))
fi
}
factorial 3sum() {
if [[ $1 -eq 0 ]]; then
echo 0
else
echo $(( $1 + sum $(( $1 - 1 )) ))
fi
}
sum 3list_files that prints all files in a directory and its subdirectories. Which approach correctly handles recursion and avoids infinite loops?Pass the test and this pattern moves unknown