Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
328 views

Shell Script To Add Two Integers

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 reads two numbers from command line arguments and calculates their sum. The third takes input from the user at runtime, calculates the sum, and displays the result.

Uploaded by

Karun Behal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
328 views

Shell Script To Add Two Integers

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 reads two numbers from command line arguments and calculates their sum. The third takes input from the user at runtime, calculates the sum, and displays the result.

Uploaded by

Karun Behal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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