so im just starting to get into the basics of bash scripting
yes this is for a class, no i dont want the answer, i want to understand
im a networking major, and as such not really big into programming

basically i need to make a simple calculator that handles + - * / and exponents

i have that part down

the next part is error checking to see if the arguments passed are the right number...have that down as well

where i am stuck is the last kind of error checking i have to do is if my $2, the operand (plus, minus, times, over, pow) is valid

i have an if statement that checks for plus, and that works...but i cant seem to figure out how to incorporate the other operands in there, it just starts spitting nonsense at me

i thought maybe i could do something like if [ $2 != "plus" || $2 != "minus" || etc ] but it doesnt seem to like that either...nested ifs didnt seem to work either...

would someone please point me in the right direction?


if [ $# -gt 3 ]
echo "Invalid number of arguments, exiting"
exit 0

if [ $2 != "plus" ]
echo "Invalid operator, use plus, minus, times, over, or pow"
exit 0

if [ $2 = "plus" ]
echo $(($1+$3))

elif [ $2 = "minus" ]
echo $(($1 - $3))

elif [ $2 = "times" ]
echo $(($1 * $3))

elif [ $2 = "over" ]
echo $(($1 / $3))

elif [ $2 = "pow" ]
echo $(($1 ** $3))


Your operator error condition should be the final else: if the operator hasn't been handled by that point, the user needs a wheelchair because she entered an invalid operator. It isn't this, or that, or the other thing; ergo it's an invalid op.

You might find the 'case' statement with its default case more useful and more readable in this instance.

Oh and, in bash, '||' means something completely different. You probably want '-or'.

you know i actually wound up using case statements

yeah teh error checking wasnt cause i wanted to, it was part of the assignment

thanks anyawys

This article has been dead for over six months. Start a new discussion instead.