Some times it require to add numbers in shell script. This post will give you a glimpse on adding two numbers.

Many ways we can achieve this. Below are some ways to do this.
1)Taking input from user, using read command
2)Through positional parameters

Through read command:

#!/bin/bash

read -p “Please enter two values, with spaces between them: ” NUM1 NUM2
printf “The sum of two given numbers is %dn” $((NUM1+NUM2))

Explanation: The script takes two values from read command pass it to bash/ksh arithmetic operator $(()), which will take care of adding them.

Through positional parameters

#!/bin/bash

[[ $# -ne 2 ]] && { echo “Please execute the script as ./$0 num1 num2”;exit; }
printf “The sum of two given numbers is %dn” $(($1+$2))

Explanation: The first line check for user inputs, and exit’s if user do not given two numbers. The second line will do automatic operations.

In our next post we will see how to add multiple numbers.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.