Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Bash Scripting - making a calculator

$
0
0
am trying to make a calculator. The user Enters number 1, chooses and operation, enters number 2, then chooses another operation or for the answer to be displayed.

eg. 1 + 1 = or 1 + 1 + 2 + 1 =

Both of these should be possible.


read -p "what's the first number? " n1
PS3="what's the operation? "
select ans in add subtract multiply divide equals; do
case $ans in 
    add) op='+' ; break ;;
    subtract) op='-' ; break ;;
    multiply) op='*' ; break ;;
    divide) op='/' ; break ;;
    *) echo "invalid response" ;;
esac
done
read -p "what's the second number? " n2
ans=$(echo "$n1 $op $n2" | bc -l)
printf "%s %s %s = %s\n\n" "$n1" "$op" "$n2" "$ans"

exit 0



This is what I have written so far, but i cannot work out how to make it possible to let the user choose 'equals' or to loop back round to enter another operation. Any ideas what I can do to my code here? I have been stuck on this all day.

I dont want the user to enter the equation themselves, i want them to be choosing from a list.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>