Add two numbers in a Shell Script

In this article, we would cover how we can add two numbers in a Shell Script. We will take BASH as reference for writing Shell Scripts. There are two ways, which would let us add two numbers in a Shell Script –

  1. through built-in let command,
  2. expr command.

Add two numbers in a Shell Script with let command

Method I. First, we will see how to add two numbers with build-in let command. Open a text editor, and we have used nano text-editor –

nano add.sh

And, append the following code –

#!/bin/bash
read -p "Enter first number: " a
read -p "Enter second number: " b

let addition=$a+$b
echo "The addition of numbers $a and $b is: " $addition

Save and exit the file.

We explain what we are trying with the above code next.

The first line – #!/bin/bash makes sure that BASH command-line interpreter will be used. read built-in bash command is to get the input from the user and store it in variables a and b. Thereafter, we use let built-in command to add the values stored in both the variables. Lastly, we use echo command to print the output.

To execute the shell script

bash add.sh

It will prompt us to input the numbers and will show us the relevant output. If you want to know more about Executing shell scripts.

Add two numbers in a Shell Script with expr command

Method II. Alternatively, we can also use expr command. We would like to add here that, since we have already covered the file creation and execution of the script above. Therefore, in this section we stick with necessary changes we bring to code. Rest is all the same.

#!/bin/bash
read -p "Enter first number: " a
read -p "Enter second number: " b

addition=`expr $a + $b`
echo "The addition of numbers $a and $b is: " $addition

We continue with the above example. Just that in place of let built-in command, we have used expr command to add two variables. expr is used to evaluate expressions and then provide us the output. Again, rest of the code we have already covered in Method I.

Note: We advise you to take care of the empty space between the code. Otherwise, the code may not work as intended.

In conclusion, we have discussed how we add two numbers in a Shell Script. Here, we used BASH as reference.

Similar Posts