You are on page 1of 2

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:

$ ./sum.sh 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

You might also like