-1

I am very new to Linux and am taking a course in it. Very excited to learn more. I am working on a script that asks user for two numbers, then asks whether user wants to add or subtract. I failed the assignment, but am still trying to figure out where I went wrong. I'm sure it's something obvious and stupid, but I can't see it.

This is one place I am sure I am messing up. I declared two variables at top, but I suspect that's not where they should be.

Here is the rest of it. When I debug, I can tell it does the math, but I cannot get it to print the answer to the console.

sum=$(expr "$number1" + "$number2")
difference=$(expr "$number1" - "$number2")
echo "Please enter your first number
    read number1
echo "Please enter your second number."
  read number2
echo "Enter S if you want to Subtract, A if you want to Add."
  read request
case " $request" in
"A") echo "$sum";;
"S") echo "$difference";;
*) "Sorry, that is an invalid request.";;
esac
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
IWhite
  • 11
  • You're not just declaring variables at the top, you're performing command substitutions, which will be evaluated immediately i.e. with the current - possibly uninitialized - values of number1 and number2. You appear to be expecting some sort of delayed evaluation - which doesn't happen in bash, AFAIK (although you might be able to implement a hacky version using eval). – steeldriver May 29 '16 at 22:43
  • That's what I was thinking is happening, but that's not what I want it to do. How would I get it to use the expression correctly and spit out the number? – IWhite May 29 '16 at 22:58
  • In your coursework, was anything taught about how variables were defined? Perhaps you should consider talking to your teacher about this? Your code is like someone bringing you your meal at a restaurant before they ask you what you want. – jsbillings May 29 '16 at 23:13
  • 1
    You'd probably benefit by searching out some of the answers to related questions on this site - for example how can I add (subtract, etc.) two numbers with bash? – steeldriver May 29 '16 at 23:35

1 Answers1

-1

In your case statement, replace "A" with A, and "S" with S:

echo "Enter S if you want to Subtract, A if you want to Add."
read request
case "$request" in
    A) echo "$sum";;
    S) echo "$difference";;
    *) "Sorry, that is an invalid request.";;
esac
alecdwm
  • 99
  • 1
    Please don't forget to explain why you are suggesting this change and why the original code doesn't work as intended. – n.st May 29 '16 at 23:44