Write a bash script that takes two arguments as command-line arguments for the above arithmetic operations (add, sub, mul, div and exp). The first argument should be the name of the operations, ie. -- ‘add’, ‘sub’, ‘div’, and ‘exp’. The subsequent arguments should be two (or more) operands. Thus, depending upon the operations requested, you may call the appropriate function (bash subroutine), which should perform the corresponding arithmetic operation, using the supplied arguments.
#!/bin/bash
add () {
echo $(( $1 + $2 ))
}
sub () {
echo $(( $1 - $2 ))
}
mul () {
echo $(( $1 * $2 ))
}
div () {
echo $(( $1 / $2 ))
}
exp () {
if [ $2 -eq 0 ]
then
echo 1
else
p=$(( $2 - 1 ))
x=$( exp $1 $p )
(( x *= $1 ))
echo $x
fi
}
if [ $1 == "add" ]
then
x=$( add $2 $3 )
elif [ $1 == "sub" ]
then
x=$( sub $2 $3 )
elif [ $1 == "mul" ]
then
x=$( mul $2 $3 )
elif [ $1 == "div" ]
then
x=$( div $2 $3 )
elif [ $1 == "exp" ]
then
x=$( exp $2 $3 )
fi
echo $x
Comments
Leave a comment