1

I am trying to learn shell scripting and following the tutorials on tutorialspoint when I came across this problem with arithmetic comparison.

$VAL1=10
$VAL2=20
$VAL3=10

if [ $VAL1 == $VAL2 ]
then
    echo "equal"
else
    echo "not equal"
fi

but I got a [: ==: unexpected operator I am not sure why the comparison operator did not work. I know I can also use rational operators, but I want to know why '==' is not defined.

2
  • as your title says ksh (but your tag says bash) , you can use == inside of (( ... == ... )) tests (which I also believe are OK in bash). Good luck. Commented Dec 3, 2012 at 2:03
  • @Jack: Did the answer solved the problem? If so, can you please accept it to mark the question as solved? Commented Jan 23, 2016 at 22:22

1 Answer 1

11

You want to change it to:

VAL1=10
VAL2=20
VAL3=10

if [ "$VAL1" -eq "$VAL2" ]
then
    echo "equal"
else
    echo "not equal"
fi

Explanations:

  • Don't add the $ for the lvalue (variable being assigned) in an assignment.
  • Always wrap your variables with double-quotes in tests. The [: ==: unexpected operator error you got is because, since VAL1 / VAL2 were not assigned properly earlier, ksh expansion of your test actually ends up resolving to this: if [ == ] - (but you see that it's actually not a problem about == being undefined)
  • Use the following for numeric comparisons instead of the == notation:
    • -eq (==)
    • -ne (!=)
    • -gt (>)
    • -ge (>=)
    • -lt (<)
    • -le (<=)
Sign up to request clarification or add additional context in comments.

1 Comment

@Jack np =) if you've found the answer useful, you can upvote it / accept it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.