Making a calculator that can loop - Bash [closed] - linux

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I 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.

Essentially you have to put a loop around that code so it reads a number then selects an operation repeatedly. Build up the formula. When the user selects "equals", break out of the outer loop and evaluate the formula. In pseudo-ish code:
formula=""
while true; do
get a number
formula+="$number"
select an operation
case $op in
...
equals) break 2 ;; # need to break out of 2 levels, the select and the while
esac
done
formula+="$op"
done
ans=$(bc -l <<< "$formula")
printf "%s = %s\n" "$formula" "$ans"

I would let the user enter the whole equation in one read. eg
read -p "enter equation" equate
ans=$(bc -l <<< "${equate%%=*})"
echo ${equate%%=*} = $ans
the <<< is a here string, the contents of the string are fed to cmd as stdin.
the %%=* in the equate variable strips of any thing after a = that may have been put in.

#!/bin/bash
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

Related

BASH scripting - menu not showing echos

I'm extremely new to this, but can anyone tell me why when I run this, it doesn't show my echo's?
It accepts all my inputs, but say when I do the subtraction one it doesn't display
echo "$a - $b = $(($a-$b))"
It worked if I put an Exit after each case, but I would like it to keep going after it completes one input.
#!/bin/bash
while true; do
clear
cat <<EOF
Please Select:
Option 1. Quit
Option 2. Display Options Again
Option 3. Subtraction
Option 4. Division
Option 5. Who am I?
EOF
read -p "Enter selection [1-5] > "
case "$REPLY" in
1)
break
;;
2)
;;
3)
read -p "Enter the First Number: " a
read -p "Enter the Second Number: " b
echo "$a - $b = $(($a-$b))"
;;
4)
printf "Enter the First Number: "
read a
printf "Enter the Second Number: "
read b
echo "$a / $b = $(($a/$b))"
;;
5)
echo "My name is Michelle"
;;
*)
echo "Invalid entry."
;;
esac
done
echo "Program terminated."
Any help would be greatly appreciated.
Problem here is that the first command in the loop is clear. This removes the output immediately after it was displayed.

Optional commands in UNIX

I'm trying to create a session in unix that will allow my to ask a simple question and then ask different questions varying on the answer.
For example if I were to ask
'Enter a choice (quit/order)'
if 'quit' is entered then program should close
if 'order' is entered then the program should continue asking further questions.
If you can help that would be great! Thanks!
#!/bin/bash
echo "Lots of choices.."
read -p "What is your choice? " choice
echo "Your choice was $choice"
if [ $choice == "quit" ]
then
echo "Exiting.."; exit 0
fi
if [ $choice == "order" ]
then
echo "Doing some other stuff.."
fi
This is where the shell's select command comes in handy. I'm going to assume you're using bash
PS3="Enter a choice: "
select answer in Quit Order; do
case $answer in
Quit) echo "Thanks for playing."; exit ;;
Order)
# select is like an infinite loop: you need to break out of it
break
;;
*) echo "Use the numbers to select your answer." ;;
esac
done
# carry on with the next question

Making a script to take input from a user and use error checking to test if two arguments were entered: Linux

My Linux class just started to begin scripting and I am having trouble with one of my questions. The question is as follows: Use a script to take two numbers as arguments and output their sum using bc.
This is my first script. To get the script to execute you need to do chmod +x filename
This is what I have so far:
#!/bin/bash
read -p "Enter in a numeric value: " num1
read -p "Enter in a second numeric value: " num2
if [ $# -ne 2 ] ; then
echo "Enter in two numeric arguments"
else
echo "The sum of the entered values are: "
echo "$num1 + $num2"|bc
fi
I keep running into an error. When I enter in two values it displays "Enter in two numeric arguments". It shouldn't do that because if I enter in two values, the if statement will evaluate to false and go to the else statement. Is my logic wrong or am I approaching this the wrong way?
You can use a while loop and break.
n=0
ex=""
while [ 1 ]
do
read -p "Enter read in a numeric value" num
n=$(( n + 1))
if [[ $n -eq 2 ]]
then
ex=${ex}${num}
echo "Sum of the two values are"
echo ${ex} | bc
break
else
ex=$num" + "
fi
done

calculate sum or product based on input

I am asking user to enter 2 numbers and s for sum, or "p" for product.
when I run the script I don't see any results
here is my script
#!/bin/bash
read -p "please enter two integers, s or p to calculate sum or product of this numbers: " num1 num2 result
if [ result == "s" ]
then
echo "num1+num2" | bc
elif [ result == "p" ]
then
echo $((num1*num2))
fi
You are comparing the string result, not the value of the variable result.
if [ "$result" = s ]; then
echo "$(($num1 + $num2))"
elif [ "$result" = p ]; then
echo "$(($num1 * $num2))"
fi
Inside $((...)), you can omit the leading $ because a string is assumed to be a variable name to be dereferenced.
There's no reason to use bc if you intend to restrict the inputs to integers.
To complement chepner's helpful answer, which explains the problem with the code in the question well, with a solution inspired by DRY[1]
:
# Prompt the user.
prompt='please enter two integers, s or p to calculate sum or product of this numbers: '
read -p "$prompt" num1 num2 opChar
# Map the operator char. onto an operator symbol.
# In Bash v4+, consider using an associative array for this mapping.
case $opChar in
'p')
opSymbol='*'
;;
's')
opSymbol='+'
;;
*)
echo "Unknown operator char: $opChar" >&2; exit 1
;;
esac
# Perform the calculation.
# Note how the variable containing the *operator* symbol
# *must* be $-prefixed - unlike the *operand* variables.
echo $(( num1 $opSymbol num2 ))
[1] Except for read's -p option, the solution is POSIX-compliant; it does, however, also work in dash, which is mostly a POSIX-features-only shell.

Counting calculation operations and writing them into a file from a shell script

guys. I'm new to Linux and shell scripting in general and I have a question.
I have the following simple calculator:
input="yes"
while [[ $input = "yes" ]]
do
PS3="Press 1 for Addition, 2 for subtraction, 3 for multiplication and 4 for division: "
select math in Addition Subtraction Multiplication Division
do
case "$math" in
Addition)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 + $num2`
COUNTER=COUNTER+1
echo Answer: $result
break
;;
Subtraction)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 - $num2`
echo Answer: $result
break
;;
Multiplication)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 * $num2`
echo Answer: $result
break
;;
Division)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=$(expr "scale=2; $num1/$num2" | bc)
echo Answer = $result
break
;;
*)
echo Choose 1 to 4 only!!!!
break
;;
esac
done
done
All I want is to be able to count the operations (meaning that for a successfull operation is +1, like "2 + 5 = 7" and some counter variable goes +1.. then something else and again +1) untill the user types something to stop the calculator. Then the counter variable (which holds the total number of operations performed) should be written inside a new file. How can I do this or can someone give me an example?
You can use a counter:
set count=0 before the loop
increment the counter after successful operation with ((count++)) after checking the status ($?) of the arithmetic operation
write the count to a file with printf "%d\n" "$count" > file
Not sure why you want to write to a new file each time. If that is the desired behavior, you can generate a new filename each time. Probably, you could name your file as operation.txt.N where N is the counter.
You can add Quit as an option that user can select:
PS3="Press 1 for Addition, 2 for subtraction, 3 for multiplication, 4 for division and 5 to Quit: "
select math in Addition Subtraction Multiplication Division Quit
... existing code here ...
And add this case:
Quit)
input=no
break
;;

Resources