How to make your own calculator using shell script in Linux

Shell script is the powerhouse of Linux. We have done various things in shell scripting up to now. If you are reaching this tutorial directly and you don’t have a single clue about the shell script I recommend looking at our shell scripting section first. In this tutorial we are going to build a simple calculator which will perform the simple mathematical calculations: addition, subtraction, multiplication and division. For this, we are going to use the select statement, case statement and expr command. Select statement will help us create the menu.  Remember select only runs in Korn(ksh) shell. Case statement will help us create the structure and expr command will help us to perform mathematical calculations.

You should know the following things to make the calculator using shell script:

Creating Menu:

First, let us create the menu using the select statement.

This will create the menu and ask the user if they want to perform addition, subtraction, multiplication or division. See the output.

Calculator menu

Now we have to add the block of code between do and done using case statement which will create a full calculator.

Full Calculator:

We created the menu and now we will do the addition, subtraction, multiplication and division. After the user do what they desire, they will be asked if they want to calculate again or not. If they want to, it will start from the beginning. For this, we will use the while loop.

We have used the while loop, created the menu, perform some mathematical calculations. In the multiplication code:

The backslash(‘’) is used because * is the keyword in shell script. The shell will not understand * as the multiplication sign. Thus, to let know the shell script, we want multiplication out of * we used backslash.
And in the division code.

And, the scale=2 is assigned because we want decimal up to two places only. This is how our calculator looks like:

calculatorYou can also add power, modulus to the calculator. Copy the code and play with it. Enjoy calculating with your own made calculator!

0saves
Free subscription: Get updates about Linux ,Shell scripting, Command Tutorial in your inbox.
You must click confirmation link sent in email. If you don't see the email, check spam folder

Comments

  1. This one is quite informative and really helpful. I am searching a graphical menu that I can use using a mouse as well

Speak Your Mind

*