Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Read that for comparing string inside if we need to use double square brackets. Some books says that comparison can be done by =. But it works withe == also.

#!/bin/bash
a="hello"
b="world"
if [[ $a == $b ]];then
    echo "equal"
fi

Why is that?

share|improve this question
4  
Is there a question in here somewhere? If so, I'm not seeing it. = is for [. == is for [[. –  Chris Down Apr 11 '13 at 5:35
add comment

2 Answers

up vote 8 down vote accepted

[[ $a == $b ]] is not comparison, it's pattern matching. You need [[ $a == "$b" ]] for comparison. = is the same as == in any shell that supports [[...]] (introduced by ksh).

[[...]] is not standard sh syntax. The [ command is standard, and the standard comparison operator there is = (though some [ implementations also recognise ==).

Just like in any argument to any command, variables must be quoted, so:

[ "$a" = "$b" ]

In standard sh, pattern matching is done with case:

case $a in
  ($b) ...
esac

See also:

share|improve this answer
add comment

These are equivalent in bash:

[[ $x == "$y" ]]
[[ $x = "$y" ]]
[ "$x" == "$y" ]
[ "$x" = "$y" ]

The first two $x variables don't have to be quoted. Bash performs word splitting and pathname expansion inside [ but not inside [[:

$ x='a b'
$ [ -s $x ]
-bash: [: a: binary operator expected
$ [[ -s $x ]]
$ ls
$ [ a = * ]
-bash: [: a: unary operator expected
$ [[ a = * ]]
$ 

[[ $x = "$y" ]] is a string comparison but [[ $x = $y ]] is a pattern matching expression:

$ y='a*'; [[ aa = "$y" ]]; echo $?
1
$ y='a*'; [[ aa = $y ]]; echo $?
0

-eq is only meant to be used with integers:

$ [[ x.x -eq x.x ]]
-bash: [[: x.x: syntax error: invalid arithmetic operator (error token is ".x")
$ x=9; [[ "x" -eq 9 ]]; echo $?
0

See also BashFAQ/031: What is the difference between test, [ and [[ ?.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.