2
#!/bin/bash
echo "enter your choice :"
echo "1 Addition"
echo "2 subtract"
echo "3 Multiplication"
read er
echo "enter the first number : "
read a
echo "enter the second number : "
read b
if [ $er="1" ]
then
sum=`expr $a + $b`
echo "sum of two numbers is $sum"
elif [ $er="2" ]
then
sub=`expr $a - $b`
echo "the diff of two numbers is $sub"
exit 0
elif [ $er="3" ]
then
mult=`expr $a * $b`
echo "the div of two numbers is $mult"
exit 0
else
echo "invalid choice"
fi

This is a simple script for calculator. But it gets executed only till the first if statement for addition after that it doesn't execute elif statement even if the conditions are true for multiplication and subtraction.

muru
  • 72,889
  • 1
    [ $er="1" ] where say er contains 2 doesn't test if 2 equals 1, it tests if 2=1 is longer than the empty string, and it is. Also if you do/did multiplication your output calls it 'the div' which does not connote multiplication. – dave_thompson_085 Oct 05 '17 at 05:30

1 Answers1

4

You will need a space around the = in the tests, the $er=1 (for example) will otherwise not be interpreted as a comparison properly.

if [ "$er" = "1" ]           # or:  if [ "$er" -eq 1 ]
then
sum=`expr "$a" + "$b"`       # or:  sum=$( expr "$a" + "$b" )  or: sum=$(( a + b ))
echo "sum of two numbers is $sum"
elif [ etc...

Note also the quoting of the variable expansions. Later in the code you will also need to quote the * in mult=`expr $a * $b` so that it's not interpreted as a filename globbing pattern.

You may replace each expr with an equivalent $(( ... )) (arithmetic expansion). The expr has fallen out of use in the last few decades.

Backticks for command substitutions are also discouraged. The $( ... ) syntax is better in many ways. For example, it nests better:

result=$( echo $( echo a ) $( echo b ) )  # pretty much impossible with backticks

... and quoting also works better as the quotes inside and outside the $( ... ) won't interfere with each other.

See also:


You would benefit from using case ... esac in this code:

case "$er" in
    1) result=$(( a + b )); op='sum'        ;;
    2) result=$(( a - b )); op='difference' ;;
    3) result=$(( a * b )); op='product'    ;;
    *) printf 'Invalid choice: "%s"?\n' "$er" >&2
       exit 1
esac

printf 'The %s of %s and %s is %s\n' "$op" "$a" "$b" "$result"
Kusalananda
  • 333,661