0
0
Bash Scriptingscripting~20 mins

Recursive functions in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Recursive Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2: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
A120
B24
CError: command not found
D1
Attempts:
2 left
💡 Hint
Think about how factorial is defined and how recursion multiplies numbers down to 1.
💻 Command Output
intermediate
2: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
AError: maximum recursion depth exceeded
B13
C5
D8
Attempts:
2 left
💡 Hint
Remember the Fibonacci sequence starts 0,1,1,2,3,5,8...
📝 Syntax
advanced
2: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
AUsing echo inside recursion is not allowed
BIncorrect use of $(( )) for arithmetic
CMissing 'then' after the if condition
DMissing closing brace '}' for the function
Attempts:
2 left
💡 Hint
Check the if statement syntax carefully.
🚀 Application
advanced
2: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 "."
A
./a.txt
./sub/b.txt
B
a.txt
b.txt
C
./sub
./a.txt
./sub/b.txt
DError: infinite recursion
Attempts:
2 left
💡 Hint
The script prints file paths, not directories.
🔧 Debug
expert
2: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
AThe arithmetic expansion is missing in the recursive call
BThe function calls itself with the same argument, causing infinite recursion
CBash does not support recursion
DThe function lacks a base case to stop recursion
Attempts:
2 left
💡 Hint
Think about what stops recursion normally.