0

I would like to print the factorial of number read from stdin but I cannot do it this way (this prints empty line):

#!/bin/bash

factorial()
{
  if [ $1 -le 1 ]
  then
    return 1
  else
    factorial $[$1-1]
    return $[$1*$?]
  fi
}

read num

ret="$(factorial $num)"
echo "${ret}"

This way worked but I feel it's a bit worse (as I cannot save the variable for later):

factorial $num
echo $?

Why is the first method not working? (link to highly upvoted answer on SO that explains it)

Community
  • 1
  • 1
Patryk
  • 22,602
  • 44
  • 128
  • 244

1 Answers1

2

The first method works if you echo the result in the factorial function rather than trying to return it.

The $(...) syntax evaluates to the output of the command you run. Since your code, as it is, has no output, ret will be empty.

#!/bin/bash

factorial()
{
  if [ $1 -le 1 ]
  then
    echo 1
  else
    part=$(factorial $(($1-1)))
    echo $(($1*$part))
  fi
}

read num

ret="$(factorial $num)"
echo "${ret}"
Mat
  • 202,337
  • 40
  • 393
  • 406