Home Linux Shell Script to find the factorial of a given integer

Shell Script to find the factorial of a given integer

by Anup Maurya
2 minutes read

In this tutorial, we will write a shell script to find the factorial of a given integer.

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 4 is 4 * 3 * 2 * 1 = 24.

Shell scripting is a scripting language used on Unix-based operating systems. It is a powerful tool for automating repetitive tasks, managing system configurations, and manipulating files and data. Shell scripts are typically written in the bash shell, which is the default shell on most Linux distributions.

To find the factorial of a given integer using a shell script, we can use a for loop to iterate over all the positive integers less than or equal to the given integer and multiply them together.

shell script to find the factorial of a given integer

#!/bin/bash

# read the input from the user
echo "Enter a positive integer: "
read n

# initialize the factorial variable to 1
factorial=1

# iterate over all positive integers less than or equal to n
for (( i=1; i<=$n; i++ ))
do
  # multiply the factorial variable by i
  factorial=$((factorial * i))
done

# print the factorial of n
echo "The factorial of $n is $factorial"

Let’s break down the code. The first line specifies the shell interpreter to be used, which is bash in this case. The next few lines prompt the user to enter a positive integer and read it from the user using the read command.

We then initialize a variable factorial to 1. This variable will store the factorial of the given integer. We then use a for loop to iterate over all the positive integers less than or equal to n. The for loop has three parts:

  1. The first part initializes a variable i to 1.
  2. The second part specifies the condition for the loop to continue running, which is that i is less than or equal to n.
  3. The third part increments i by 1 after each iteration.

Inside the loop, we multiply the factorial variable by i and store the result back in factorial. After the loop completes, we print the factorial of n using the echo command.

To run the script, save the above code in a file with a .sh extension, such as factorial.sh. Then, make the script executable by running the following command in the terminal

chmod +x factorial.sh

You can then run the script by typing its name in the terminal

./factorial.sh

The script will prompt you to enter a positive integer, and then it will compute and print the factorial of the integer.

In conclusion, we have seen how to write a shell script to find the factorial of a given integer using a for loop. Shell scripting is a powerful tool for automating tasks, and knowing how to write shell scripts can greatly improve your productivity as a programmer or system administrator.

related posts

Leave a Comment

Enable Notifications OK No thanks