0

I am just trying to explore Bash Script since I installed Linux Mint. So I tried to create a script with conditional statement. The code works but still gives me the wrong answer.

For example:

enter image description here

Even when i chose 4 to divide the numbers, it gave me a sum.

Here is the code.

echo "Enter First Number: "
read numl 
echo "Enter Second Number: " 
read num2 
echo "Choose Operation Below" 
echo "1-Addition, 2-Subtraction, 3-Multiplication, 4-Division" 
read opr 

if [ $opr==1 ]
then 
    answer=$((numl+num2)) 
    
elif [ $opr==2 ]
then 
    answer=$((numl-num2)) 

elif [ $opr==3 ]
then 
    answer=$((numl*num2)) 

elif [ $opr==4 ]
then 
    answer=$((numl/num2)) 

else
    echo "Wrong choice of operation."
fi
echo "Answer is $answer" 

What do you think is the problem here? Any thoughts?

Carlmalone
  • 21
  • 5

1 Answers1

1

The [ command does different things depending on how many arguments it has. With just one argument, the test is "is this string not empty". That is always true for [ $opr==1 ]

Your solution: put spaces around ==


Next step: always quote your variables: you never know what garbage your users will enter.

if [ "$opr" == "1" ]; ...
glenn jackman
  • 223,850
  • 36
  • 205
  • 328