Using the C Shell, I'm building a script that will compute simple mathematical computations (addition, subtraction, multiplication, division). The user will enter two integers (operands) on the command line separated by the operation (operator) they wish to perform.
Example of the command line would be as follows: ./scriptname 5 minus 2
I have that part working perfectly. Where I'm running into a problem is the following:
1) If the any of the operands or operator are missing from the command line I want to print an error
2) If the user enters an invalid operator (not +, -, %, X) the script shall will print an error)
I've attached my script below. If you have any recommendations for the above two issues your help would be greatly appreciated. Thank you!
if ( $2 =~ "plus" ) then
@ c = $1 + $3
echo "The sum is: $c"
else if ( $2 =~ "minus" ) then
@ c = $1 - $3
echo "The difference is: $c"
else if ( $2 =~ "div" ) then
@ c = $1 / $3
echo "The quotient is: $c"
else if ( $2 =~ "times" ) then
@ c = $1 * $3
echo "The product is: $c"
else if ( ( $2 !~ "plus" || $2 !~ "minus" ) && ( $2 !~ "div" || $2 !~ "times" ) ) then
echo "You have entered an invalid operation"
else
echo "You are missing an operand or operator"
endif
Thank you, Carona. I'll try that but would like to learn how to do it both ways. I'm learning UNIX through a book I bought and this was one of the exercises. Clearly - I'm not very good at it.
CSH is not UNIX, it's a nonstandard language which was popular in the early 80's(it supported "fancy" things like line editing!) but has only clung to a weird, tenuous life since then -- mostly through it being forcefed to new students through badly out-of-date textbooks. Occasional old systems still run it to use scripts old enough to be having mid-life crises. Kind of the UNIX equivalent of qbasic.
These days a proper UNIX shell has all the same advantages with none of the notorious design flaws.
I generally refuse to use csh and its derivatives for reasons already mentioned in this thread... But, I think you want to change:
else if ( $2 =~ "times" ) then
@ c = $1 * $3
echo "The product is: $c"
else if ( ( $2 !~ "plus" || $2 !~ "minus" ) && ( $2 !~ "div" || $2 !~ "times" ) ) then
echo "You have entered an invalid operation"
else
echo "You are missing an operand or operator"
endif
to something like:
else if ( $2 =~ "times" ) then
@ c = $1 * $3
echo "The product is: $c"
else echo "You have entered an invalid operation"
exit 2
endif
and I think you want to add something like:
if ( $# < 3 ) then
echo "You are missing an operand or operator"
exit 1
endif
before the code you showed us. I have not tested any of these suggestions, but they should get you a little bit closer to what you're trying to do.
If you want to learn about UNIX and Linux (and BSD) system shell programming, I strongly suggest you get a different book that describes ksh , bash , or some other shell that is based on Bourne shell syntax.