1). ANSWER :
GIVENTHAT :
To Write a short bash script that takes in two arguments
from a user, asks the user whether they would like to add,
subtract, multiply, or divide. Each of these operations must be a
function that returns data.
The required script is given below -
Explanation -
- In this code there are four functions for each operation which
calculates the result in result variable and returns it back
- User enters two numbers num1 and num2 along with the operation
"+", "-", "*" and "/".
- The $oper variable is compared against the four operators and
calculates result to which it matches.
- In every if condition branch the function is called as Sum
$num1 $num2 where $num1 and $num2 are parameters to the function.
Inside sum the parameters are fetched by $1 and $2 where $1 is
$num1 and $2 is $num2 .
#!/bin/bash
# Code to ask numbers from user and perform operations
like, +,-,*,/
#function to add
Sum(){
result=$(echo "$1 + $2"|bc)
return $result
}
#function to subtract
Subtract(){
result=$(echo "$1 - $2"|bc)
return $result
}
#function to multiply
Multiply(){
result=$(echo "$1 * $2"|bc)
return $result
}
#function to divide
Division(){
result=$(echo "$1 / $2"|bc)
return $result
}
#reading two numbers and operation
read -p "Enter first number : " num1
read -p "Enter second number : " num2
read -p "Enter the operation : " oper
result=0
#checking for operations and calling the corresponsing
function
if [ "$oper" = "+" ]
then
Sum $num1 $num2
result=$?
echo "The sum is : $result "
fi
if [ "$oper" = "-" ]
then
Subtract $num1 $num2
result=$?
echo "The Difference is : $result "
fi
if [ "$oper" = "*" ]
then
Multiply $num1 $num2
result=$?
echo "The Multiplication result is : $result "
fi
if [ "$oper" = "/" ]
then
Division $num1 $num2
result=$?
echo "The result of division is : $result "
fi
|
Refer to the screenshot below for code and output -
Output -