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
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:
- The first part initializes a variable
- The second part specifies the condition for the loop to continue running, which is that
iis less than or equal to
- The third part increments
iby 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
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
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.