Shell Script to Find Factorial of Number Using For & While Loop on Command Line Full Tutorial For Beginners

 

 

factorial.sh

 

 

using while loop

 

 

#shell script for factorial of a number
#factorial using while loop

echo "Enter a number"
read num

fact=1

while [ $num -gt 1 ]
do
  fact=$((fact * num))  #fact = fact * num
  num=$((num - 1))      #num = num - 1
done

echo $fact

 

 

 

using for loop

 

 

#shell script for factorial of a number
#factorial using for loop

echo "Enter a number"
read num

fact=1

for((i=2;i<=num;i++))
{
  fact=$((fact * i))  #fact = fact * i
}

echo $fact

Leave a Reply