Skip to main content

Basic Shell script to perform Mathematical functions

 #!/bin/bash

: '
 BASH Script that mimics a 4 function calculator. A function called addition. This function will 
take two arguments and will return the sum of these two arguments. Be sure to check
 that the values are valid numbers. A function called subtraction. This function will take two 
arguments and will return the difference of these two arguments. A function called multiply. 
This function will take two arguments and will return the product of these two arguments.
A function called divide. This function will take two arguments and will return the 
quotient of these two arguments. First argument is an option that chooses what to do with the
 two other arguments. The options should be as follows: -a Perform addition of the two numbers -s
 Perform subtraction of the two numbers -m Perform multiplication of the two numbers -d Perform 
division of the two numbers Second argument should be the first number used for the math problem 
Third argument should be the second number used for the math problem Examples: To add 10 + 2, run 
the script as follows: math.sh -a 10 2 To subtract 10 - 2, run the script as follows: math.sh -s 
10 2 To multiply 10 x 2, run the script as follows: math.sh -m 10 2 To divide 10 / 2, run the 
script as follows: math.sh -d 10 2 Modify your functions so it works with floating point numbers 
(can accept and return the fractional part of numbers)
'


addition(){


for i in "$@"

do 

case "${i#[-+]}" in 

*[!0-9.]* | '')

echo "Not Numbers!"

exit 2

;; 

esac

done

#echo $(($1+$2))

echo "$1 + $2" | bc



}



subtraction(){


for i in "$@"

do 

case "${i#[-+]}" in 

*[!0-9.]* | '')

echo "Not Numbers!"

exit 2

;; 

esac

done

#echo $(($1-$2))

echo "$1 - $2" | bc


}


multiply(){


for i in "$@"

do 

case "${i#[-+]}" in 

*[!0-9.]* | '')

echo "Not Numbers!"

exit 2

;; 

esac

done

#echo $(($1*$2))

echo "$1 * $2" | bc


}


divide(){


for i in "$@"

do 

case "${i#[-+]}" in 

*[!0-9.]* | '')

echo "Not Numbers!"

exit 2

;; 

esac

done

if ! [[ $2 =~ ^[1-9][0-9].*$ ]]

    then

        echo "Sorry greater then zero"

exit

fi

#echo $(($1/$2))

echo "$1 / $2" | bc


}





while getopts "a:s:m:d:" options

do

case $options in

a)

addition $2 $3

;;

s)

subtraction $2 $3


;;

m)

multiply $2 $3


;;

d)

divide $2 $3



;;

?)

echo "Invalid Flag Provided!"

exit

esac

done




Comments