Shell script to find factorial of a number - Manoj Jha

Manoj Jha

Robotic Process Automation, Abbyy Flexicapture, Python, JavaScript, C#. Machine learning and Data Science

Shell script to find factorial of a number

Share This

You can create a shell script to find the factorial of a number using a while loop. Here is an example:

In this script, we prompt the user to enter a number and store it in the variable number. We then initialize two variables, factorial and counter, to 1 and the value of number, respectively.

We use a while loop to iterate through the numbers from the value of number down to 1. In each iteration, we multiply the current value of factorial by the current value of counter, then decrement the value of counter by 1.

At the end of the loop, we output the final value of factorial, which is the factorial of the number entered by the user. You can execute this script by making it executable by running chmod +x scriptname and then you can run ./scriptname.

Make sure that you have bash installed in your system, otherwise, you have to use a different shell accordingly.


This script uses a for loop to iterate from 1 to the given number, and calculates the factorial by multiplying the current iteration value with the previous result.

The script starts by using the "echo" command to print a message asking the user to enter a number, and then uses the "read" command to read the user's input and store it in the "num" variable.

Then, it initializes a variable "fact" with a value of 1.

The script then enters a for loop, where i starts at 1, and continues until i is less than or equal to the user input num. At each iteration, the current value of i is multiplied with the previous result, and the result is stored in the fact variable.

Finally, after the loop finishes, the script uses the "echo" command to print the final result, which is the factorial of the given number.

Please note that this is just an example, you can also use recursive function or while loop to find the factorial of a number using shell script, the above code is for educational purpose only.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

If the post was helpful to you, Please donate us so we can create more useful content

Support by Donate

Pages