fork download
  1. #!/bin/bash
  2. # your code goes here
  3. factorial_recursive() {
  4. local n="$1"
  5. if [ "$n" -lt 0 ]; then
  6. echo "Factorial is not defined for negative numbers"
  7. return 1
  8. elif [ "$n" -le 1 ]; then
  9. echo 1
  10. else
  11. local prev=$((n - 1))
  12. local result=$(factorial_recursive "$prev")
  13. echo $((n * result))
  14. fi
  15. }
  16.  
  17. echo "enter a number"
  18. read num
  19. result=$(factorial_recursive "$num")
  20. echo "the factorial of the given number is $result"
Success #stdin #stdout #stderr 0.01s 5292KB
stdin
Standard input is empty
stdout
enter a number
the factorial of the given number is 
stderr
./prog.sh: line 5: [: : integer expression expected
./prog.sh: line 8: [: : integer expression expected
./prog.sh: line 13: Factorial is not defined for negative numbers: syntax error in expression (error token is "is not defined for negative numbers")