0

Here I want to use the value given by the user it is stored in variable n and I want to use it in my recursive function to make a loop

My code

echo "Enter the Number to find the Factorial"
read n
fact = 1;
function factorial(n) {
  if [ $n -eq 0 ]; then
    echo $fact
  else
    fact=$(($fact * $n))
    factorial $(($n - 1))
  fi
}

This is the error which is shown syntax error near unexpected token `x'

  • 2
    There is no `x` in your code and that code would produce more error messages than that one. Please post the real error message from the code you posted or the real code that produces that error message so we can help you but first, as the [bash](https://stackoverflow.com/tags/bash/info) tag you added tells you: `For shell scripts with syntax or other errors, please check them at https://shellcheck.net before posting here.`. – Ed Morton Jul 22 '22 at 14:47
  • Related: https://stackoverflow.com/questions/9682524/recursive-function-in-bash – kvantour Jul 22 '22 at 14:50
  • 2
    Functions do not allow for defined parameters; all functions simply accept whatever arguments are passed when they are called and accessed via the positional parameters `$1`, `$2`, `$@`, `$*`, etc. – chepner Jul 22 '22 at 14:58

1 Answers1

1

Below is a corrected version of your script. Note that I'm mostly sticking to your style. Personally, I wouldn't write a script like that.

#!/bin/bash

echo "Enter the Number to find the Factorial"
read -r n
fact=1
factorial() {
  if [ "$1" -eq 0 ]; then
    echo $fact
  else
    fact=$((fact * $1))
    factorial $(($1 - 1))
  fi
}

factorial "$n"
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
  • Thank you so much @M. Nejat Aydin. Actually it's my class Assignment and u know that the all use the traditional ways of programming. And what does -r do here – Shaik Mohammed Huzaifa Jul 22 '22 at 16:28