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?

#!/bin/bash

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

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

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

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

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

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

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

fi

Recommended Answers

All 2 Replies

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.