Jay
Jay

Reputation: 63

How to write a shell script that will add two numbers?

Assuming that the inputs are given as command line arguments and if two numbers are not given show a error message as "command line arguments are missing".

Sample output:

addition of 1 and 2 is 3.

Upvotes: 2

Views: 42484

Answers (5)

samar ranjan Nayak
samar ranjan Nayak

Reputation: 131

Just to put all in one place.

num1=10 
num2=20 
 
sum=$(( $num1 + $num2 )) 
 
sum=`expr $num1 + $num2` 
 
sum=$[num1+num2] 
 
sum=$(echo $num1 $num2 | awk '{print $1 + $2}') 
 
sum=$(expr $num1 + $num2) 
 
sum=$(expr "$num1" + "$num2") 

Upvotes: 0

Sagar Jadhav
Sagar Jadhav

Reputation: 1119

actualNumber=720; incrementNo=1;

actualNumber=$(expr "$actualNumber" + "$incrementNo");

echo $actualNumber

Upvotes: 2

Harini
Harini

Reputation: 571

DESCRIPTION: This script will read two integer value from users and give output as sum of two values SCRIPT:

#!/bin/bash

echo -n "Enter the first number : "
read num1
echo -n "Enter the second number : "
read num2
sum=`expr $num1 + $num2`
echo "sum of two value is $sum"

RUN:

sh sum.sh

Upvotes: 0

tso
tso

Reputation: 4924

#!/bin/bash
if [ $# -lt 2 ]
then
    echo "command line arguments are missing "
else
    echo $(($1+$2))
fi

Upvotes: 3

justaguy
justaguy

Reputation: 3022

In awk:

echo 5 5 | awk  '{ print $1 + $2}'
10

Upvotes: 3

Related Questions