Find Factorial of a Number in Bash
A factorial program multiplies a non-negative integer by every positive integer below it. In this tutorial, you will learn how to calculate the factorial of a number in Bash using a while loop, a for loop, command-line input, and a reusable function.
The factorial of n is written as n! and is defined as:
n! = n × (n - 1) × ... × 2 × 1forn > 00! = 1
For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
Find Factorial Using a Bash While Loop
In this example, a while loop repeatedly multiplies the current value of counter with factorial. The counter is decremented after each iteration until it reaches zero.
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 calculated.
factorial is initialized to 1 because multiplication by zero would make the result zero.
counter is a temporary copy of the given number. It is decremented inside the loop, while the original value in num remains unchanged.
When counter becomes zero, the loop stops and the accumulated result is printed.
Output
$ ./bash-factorial
120
Calculate Factorial Using a Bash For Loop
A C-style Bash for loop can count upward from 1 to the entered number. During each iteration, the current loop value is multiplied by the accumulated factorial.
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
If the user enters 0, the loop does not run and factorial remains 1, which correctly represents 0!.
Output
$ ./bash-factorial
Enter Number
5
Factorial of 5 is 120
Bash Factorial Program with Input Validation
A factorial is defined only for non-negative integers in this program. The following script checks the input before performing the calculation.
#!/bin/bash
read -r -p "Enter a non-negative integer: " num
if [[ ! $num =~ ^[0-9]+$ ]]; then
echo "Error: enter a non-negative integer."
exit 1
fi
factorial=1
for ((i = 2; i <= num; i++)); do
factorial=$((factorial * i))
done
printf '%d! = %d\n' "$num" "$factorial"
The regular expression ^[0-9]+$ accepts one or more digits and rejects negative values, decimal numbers, empty input, and non-numeric text.
Example output for valid input
Enter a non-negative integer: 6
6! = 720
Example output for invalid input
Enter a non-negative integer: -3
Error: enter a non-negative integer.
Pass the Number as a Bash Command-Line Argument
For scripts used in automation, it is often more convenient to pass the number as the first command-line argument instead of entering it interactively.
#!/bin/bash
num=${1:-}
if [[ ! $num =~ ^[0-9]+$ ]]; then
echo "Usage: $0 NON_NEGATIVE_INTEGER" >&2
exit 1
fi
factorial=1
for ((i = 2; i <= num; i++)); do
factorial=$((factorial * i))
done
echo "$factorial"
Save the script as bash-factorial, make it executable, and provide the number when running it.
chmod +x bash-factorial
./bash-factorial 5
Output
120
Create a Reusable Factorial Function in Bash
A function keeps the factorial logic separate from input handling. This is useful when the calculation must be called multiple times in a larger script.
#!/bin/bash
factorial() {
local num=$1
local result=1
local i
for ((i = 2; i <= num; i++)); do
result=$((result * i))
done
printf '%d\n' "$result"
}
value=5
result=$(factorial "$value")
echo "Factorial of $value is $result"
The variables declared with local exist only inside the function, which prevents them from unintentionally changing variables elsewhere in the script.
Bash Integer Limit for Large Factorials
Bash arithmetic uses fixed-width signed integers provided by the shell and system architecture. A factorial grows quickly, so sufficiently large input values can overflow and produce an incorrect result.
For factorials beyond Bash integer capacity, use an arbitrary-precision calculator such as bc.
#!/bin/bash
read -r -p "Enter a non-negative integer: " num
if [[ ! $num =~ ^[0-9]+$ ]]; then
echo "Error: enter a non-negative integer."
exit 1
fi
factorial=1
for ((i = 2; i <= num; i++)); do
factorial=$(printf '%s * %s\n' "$factorial" "$i" | bc)
done
echo "$num! = $factorial"
This version requires the bc utility to be installed on the system.
Common Bash Factorial Errors
- Initializing the result to zero: Use
factorial=1; otherwise, every multiplication produces zero. - Accepting negative or decimal input: Validate the value as a non-negative integer before running the loop.
- Using an unquoted input variable outside arithmetic expressions: Quote ordinary variable expansions to avoid unwanted word splitting.
- Ignoring integer overflow: Use an arbitrary-precision tool when calculating large factorials.
- Changing the original input unintentionally: Use a separate counter variable if the original number is needed later.
Questions About Bash Factorial Programs
What is the factorial of zero in Bash?
The factorial of zero is 1. If the result variable starts at 1, a loop with zero iterations returns the correct value automatically.
Can Bash calculate the factorial of a negative number?
The iterative programs shown here accept only non-negative integers. Negative integer factorials are not defined by the standard factorial operation used in these scripts.
Should a Bash factorial program use a for loop or while loop?
Both loops produce the same result. A for loop is concise when the number of iterations is known, while a while loop makes the counter update explicit.
Why does a large factorial become negative in Bash?
A negative or otherwise unexpected result can occur when the calculation exceeds the maximum integer value supported by Bash arithmetic. Use bc or another arbitrary-precision tool for larger values.
Verify the Bash Factorial Script
- Confirm that input
0returns1. - Confirm that input
1returns1. - Confirm that input
5returns120. - Check that negative values, decimals, empty input, and text are rejected by validated versions.
- Test the largest expected input and check for Bash integer overflow.
Conclusion
In this Bash Tutorial, we learned how to find the factorial of a number using while and for loops, validate user input, accept a command-line argument, create a reusable function, and handle values that exceed Bash integer capacity.
TutorialKart.com