Pages

Monday, December 17, 2012

Shell script: Add two numbers

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 %d\n" $((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 %d\n" $(($1+$2))

Explanation: The first line check for user inputs, and exits 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.

0 comments:

Post a Comment