Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to create a shell script and pass three arguments in the format number operator number ,example:25 * 25 and perform calculation based on the operator and if operator not present then dispaly Unknown operator. How can it be done ??

What I have tried:

#!/bin/sh
result=0
if [$2 = + ]
then
result=$(($1 + $3))
echo $result
elif [$2 = - ]
then
result=$(($1 - $3))
echo $result
elif [$1 * $3 ]
then
result=$(($1 * $3)
echo $result
else
echo "Unknown Operator"
fi
Posted
Updated 11-Feb-21 1:44am

1 solution

This is similar to your question of yesterday and a few simple typing errors need fixing:
Bash
#!/bin/sh
result=0
if [ "$2" = + ]
then
	result=$(($1 + $3))
	echo $result
elif [ "$2" = - ]
then
	result=$(($1 - $3))
	echo $result
elif [ "$2" = x ]
then
	result=$(($1 * $3))
	echo $result
else
	echo "Unknown Operator"
fi

Note, as I mentioned yesterday the expressions in square brackets require spaces after the opening bracket and before the closing one. And $((e)) expressions require two closing parentheses. Please try at least desk checking your code.

And the '*' character has a special meaning to the shell so cannot be used in the command line. I have used a small x instead.
 
Share this answer
 
v4
Comments
Richard MacCutchan 12-Feb-21 3:12am    
When your code does not do what you expect then read through it carefully. Look at each line and check that the syntax is correct: spaces, correct brackets and the right number, any other special characters etc. Use the documentation to ensure you are using code correctly. In your case writing simple shell scripts, you should check the man page for bash (type "man bash" at the terminal prompt) and read through it a few times to check all the rules.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900