Shell Script to Add Two Integers
Brief: This example will help you to understand to add two numbers in the bash script. This script takes the input of two numbers from the user and prints the sum of both numbers.
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 2 3 4 5 6 7 8 9 10 | #!/bin/bash # Calculate the sum of two integers with pre initialize values # in a shell script a=10 b=20 sum=$(( $a + $b )) echo $sum |
Command Line Arguments
In this second example, shell script reads two numbers as command line parameters and perform the addition operation.
1 2 3 4 5 6 7 | #!/bin/bash # Calculate the sum via command line arguments # $1 and $2 refers to the first and second argument passed as command line arguments sum=$(( $1 + $2 )) 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 2 3 4 5 6 7 8 9 | #!/bin/bash # Take input from user and calculate sum. read -p "Enter first number: " num1 read -p "Enter second number: " num2 sum=$(( $num1 + $num2 )) echo "Sum is: $sum" |
Output:
Enter first number: 12 Enter second number: 15 Sum is: 27