Build a bash script in Unix to simulate a calculator.
It should behave like this:
Enter numone: 4
Enter operator: +
Enter numtwo: 4
4 + 4 = 8
Enter operator: -
Enter numtwo: 4
8 - 4 = 4
Enter operator: MS
4 -> M
Enter operator: *
Enter numtwo: -2
4 * -2 = -8
Enter operator: C
results cleared
Program ends once "exit" is entered.
It will work like regular calculator which will only ask for first operand once. The result from previous calculation will become the value for first operand.
# !/bin/bash
# Take user Input
operator="X"
echo "Enter first number : "
read a
while true; do
echo "Enter operator:"
read operator
if [ "$operator" != "exit" ];
then
echo "Enter second number:"
read b
fi
case $operator in
"+")res=`echo $a + $b | bc`
;;
"-")res=`echo $a - $b | bc`
;;
"*")res=`echo $a \* $b | bc`
;;
"/")res=`echo "scale=2; $a / $b" | bc`
;;
"exit") exit 0
;;
esac
echo "Result : $res"
a=$res
done
Get Answers For Free
Most questions answered within 1 hours.