Challenge - 5 Problems
Recursive Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
Output of a simple recursive factorial function
What is the output of this Bash script when run?
Bash Scripting
#!/bin/bash factorial() { if [ "$1" -le 1 ]; then echo 1 else local prev=$(factorial $(( $1 - 1 ))) echo $(( $1 * prev )) fi } factorial 5
Attempts:
2 left
💡 Hint
Think about how factorial is defined and how recursion multiplies numbers down to 1.
✗ Incorrect
The function calls itself with decreasing values until it reaches 1, then multiplies back up: 5*4*3*2*1 = 120.
💻 Command Output
intermediate2:00remaining
Output of recursive Fibonacci function
What does this Bash script print when executed?
Bash Scripting
#!/bin/bash fib() { if [ "$1" -le 1 ]; then echo $1 else local a=$(fib $(( $1 - 1 ))) local b=$(fib $(( $1 - 2 ))) echo $(( a + b )) fi } fib 6
Attempts:
2 left
💡 Hint
Remember the Fibonacci sequence starts 0,1,1,2,3,5,8...
✗ Incorrect
fib(6) = fib(5) + fib(4) = 5 + 3 = 8.
📝 Syntax
advanced2:00remaining
Identify the syntax error in this recursive function
Which option correctly identifies the syntax error in this Bash recursive function?
Bash Scripting
#!/bin/bash countdown() { if [ $1 -le 0 ] echo "Done!" else echo "$1" countdown $(( $1 - 1 )) fi } countdown 3
Attempts:
2 left
💡 Hint
Check the if statement syntax carefully.
✗ Incorrect
In Bash, an if statement must have 'then' after the condition. It's missing here.
🚀 Application
advanced2:00remaining
What is the output of this recursive directory listing script?
Given this Bash script that recursively lists files, what will it output when run in a directory with files 'a.txt' and subdirectory 'sub' containing 'b.txt'?
Bash Scripting
#!/bin/bash list_files() { for item in "$1"/*; do if [ -d "$item" ]; then list_files "$item" else echo "$item" fi done } list_files "."
Attempts:
2 left
💡 Hint
The script prints file paths, not directories.
✗ Incorrect
The script prints only files, recursively descending into directories. It prints './a.txt' and './sub/b.txt'.
🔧 Debug
expert2:00remaining
Why does this recursive function cause a stack overflow?
Examine this Bash recursive function. Why does it cause a stack overflow when called with 3?
Bash Scripting
#!/bin/bash infinite() { echo "$1" infinite $1 } infinite 3
Attempts:
2 left
💡 Hint
Think about what stops recursion normally.
✗ Incorrect
The function calls itself with the same argument endlessly, no base case to stop it, causing stack overflow.