Find Factorial in Bash
In this tutorial, we will learn how to find factorial of a given number in different ways using Bash Scripting.
Find Factorial using Bash While Loop
In this example, we will take a while loop and iterate it given number of times, while we consolidate the factorial in a variable.
Bash Script File
#!/bin/bash
num=5
factorial=1
counter=$num
while [[ $counter -gt 0 ]]; do
factorial=$(( $factorial * $counter ))
counter=$(( $counter - 1 ))
done
echo $factorial
num
stores the number whose factorial is to be calculated.
factorial
variable stores the result of factorial.
counter
is a temporary variable to store the given number and gets decremented in the while loop. If we do not use this temporary variable and use the num
variable, we might not have the track of given number.
After the control comes out of while loop, we have the result in factorial
variable.
Output
$ ./bash-factorial
120
Calculate Factorial using Bash For Loop
In the following bash script, we use for loop to calculate the factorial of given number.
Bash Script File
#!/bin/bash
echo Enter Number
#read number from terminal
read num
#initialize factorial
factorial=1
#for loop
for ((i=1;i<=num;i++))
do
factorial=$(($factorial*$i))
done
echo Factorial of $num is $factorial
Output
$ ./bash-factorial
Enter Number
5
Factorial of 5 is 120
Conclusion
In this Bash Tutorial, we learned how to find the factorial of a number using Bash Scripting.