Shell Script for Adding Two Numbers

0% found this document useful (0 votes)
182 views2 pages
This document contains 3 examples of shell scripts that calculate the sum of two numbers. The first initializes two variables with values and stores their sum in a third variable. The second…

Uploaded by

Karun Behal
  • Adding Two Integers Using Shell Script
  • Shell Script with Run Time Input

Shell Script to Add Two Integers

This is an example script initializes two variables with numeric values. Then
perform an addition operation on both values and store results in the third
variable.
1 #!/bin/bash
2 # Calculate the sum of two integers with pre initialize values
3 # in a shell script
4
5 a=10
6 b=20
7
8 sum=$(( $a + $b ))
9
10 echo $sum

Command Line Arguments


In this second example, shell script reads two numbers as command line
parameters and perform the addition operation.
1 #!/bin/bash
2 # Calculate the sum via command line arguments
3 # $1 and $2 refers to the first and second argument passed as command line arguments
4
5 sum=$(( $1 + $2 ))
6
7 echo "Sum is: $sum"

Output:

$ ./[Link] 12 14 # Executing script

Sum is: 26

Run Time Input


Here is another example of a shell script, which takes input from the user at
run time. Then calculate the sum of given numbers and store to a variable
and show the results.

1 #/bin/bash
2 # Take input from user and calculate sum.
3 read -p "Enter first number: " num1
4 read -p "Enter second number: " num2
5 sum=$(( $num1 + $num2 ))
6 echo "Sum is: $sum"
7
8
9

Output:

Enter first number: 12

Enter second number: 15

Sum is: 27

Shell Script to Add Two Integers 
This is an example script initializes two variables with numeric values. Then 
perform an a
4 
5 
6 
7 
8 
9 
read -p "Enter second number: " num2 
sum=$(( $num1 + $num2 )) 
echo "Sum is: $sum"        
Output: 
Enter

You might also like