call-me
call-me

Reputation: 726

Shell script: Why can't the if statement make a logical comparison?

I'm new to Unix and Linux in general and failed to make a logical comparison within an if statement.

I'm sure this is a very basic mistake but I just can't find the error.

if (7+3 == 10); then
    echo "nice this works"
elif (7+3 == 73); then
    echo "too bad string concatenation"
else
    echo "I really don't understand shell"
fi

Echo: I really don't understand shell.

Upvotes: 1

Views: 63

Answers (3)

glenn jackman
glenn jackman

Reputation: 247042

I would expect you to see this error message twice: 7+3: command not found -- did you?

Single sets of parentheses run the enclosed commands in a subshell, so you're attempting to execute the command 7+3 with two arguments, == and 10 (or 73)

Arithmetic evaluation occurs within double parentheses

if ((7+3 == 10)); then
     echo "nice this works"
elif ((7+3 == 73)); then
     echo "to bad string concatenation"
else
     echo "I really don't understand shell"
fi
nice this works

See http://mywiki.wooledge.org/ArithmeticExpression

Upvotes: 4

Rahul
Rahul

Reputation: 77896

The correct syntax would be

if [ $((7+3)) -eq 10 ]; then
    echo "nice this works"

Upvotes: 0

DZDomi
DZDomi

Reputation: 1679

The operator your are using == is used for string comparisons. The right way to do it would be with the -eq (equal) operator:

if [ 10 -eq 10 ]; then
    echo "10 = 10"
fi

and you also need to use the right parenthesis for the if [ ] (you can look this up in the bash with 'man test')

Upvotes: 0

Related Questions