Shell program to add two numbers using functions

Using function keyword, we can declare function in shell script.

In this tutorial, we will learn how to add two numbers using function in shell script.

Function Syntax in shell script

function fun_name ()
    #Implement the function here

To call the function, just add the function name in the script.

> fun_name

Call function with arguments in shell script

To call the function with arguments, add the argument values after the function name.


> fun_name arg1 arg2

In function $1 will refer the value of agr1, and $2 will refer the value of arg2 and so on.

1. Initialize two variables.

2. Declare and implement the addition function.

3. Call the add function with two arguments.

Add two variables using function in shell script

#$1 will have the value 10 which is the value of a
#$2 will have the value 20 which is the value of b
function add()
    sum=$(($1 + $2))
    echo "Sum = $sum"

#call the add function and pass the values
add $a $b


Sum = 30

Topics You Might Like