i am trying to write a script code in unix that will:
The problem statement, all variables and given/known data:
display following menu to user:
(A) Add
(B) Subtract
(C) Multiply
(D) Divide
(E) Modulus
(F) Exponentiation
(G) Exit
Then ask user for choice (A-F). After taking users choice ask user for two numbers and
perform chosen operation on those two numbers. The program should keep asking
for choice / numbers unless user chooses �G� for exit.
Relevant commands, code, scripts, algorithms:
The attempts at a solution (include all code and scripts):
i tried everything to write this code i couldnt
Complete Name of School (University), City (State), Country, Name of Professor, and Course Number
school name: Senaca college, Toronto, Canada, Name of Professor: peter wheeler, and Course Number: Tech 154
echo -n "Enter first number "
read a
echo -n "Enter second number "
read b
if [ $x == 'A' -o $x == 'a' ] ; then
c=$(( a + b ))
fi
if [ $x == 'B' -o $x == 'b' ] ; then
c=$(( a - b ))
fi
if [ $x == 'C' -o $x == 'c' ] ; then
c=$(( a * b ))
fi
echo "The answer is $c"
Ok i see you had did a read -p 'Please type ation:' x , that is not visible here .
You can either make sure the provided char inputs are non-caps, or use regex to catch both at once.
1) Make it small (is this posix?)
x=A
x=${x,,}
[ $x = a ] && echo "Add"
2) Or use Regex:
x=a
[ $x = [aA] ] && echo "Add"
Use either 1. or 2., this will save you from using if [ $x == 'B' -o $x == 'b' ] ; then for each of the A-F.
3) For menus or comparing 1 value with diffrent options, its quite easier to use a case statement
case $x in
a) echo "do add" ;;
b) echo "do sub" ;;
esac
4) Could use Regex here too (= instead)
case $x in
a|A) echo "do add" ;;
[bB]) echo "do sub" ;;
esac
edit: 5. Quotes:
I'd rather make the quotes around the variables, than around the letters.
If the variable is empty, or contains a special char (like arrow-up) it will produce and error message, rather than just not execute (as in not true ; not matching).
So yes, for the REGEX you need the double brackets.
BTW: bad behaviour example as i was running it as root
Edit: Yes, for anything more complex than a simple single yes/no requires a standard if-statement like:
if [ $x -ge 100 ] || [[ "$x" == [aA] ]]
then echo "Great"
else echo "Low"
fi
BTW: The only 'place' i actualy use == (as it wont work properly with a single) is with PHP.
All of both the shells (sh,bash) i came across worked well with a single =.
EDIT2:
Just read (once more) the 'man bash', and beeing in the homework section i must say:
-> Better get used to use the proper syntax right from the start!