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:
count=0
before the loop((count++))
after checking the status ( $?
) of the arithmetic operationprintf "%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
;;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.