What is the difference between =
, ==
and -eq
in shell scripting?
Is there any difference between the following?
[ $a = $b ]
[ $a == $b ]
[ $a -eq $b ]
Is it simply that =
and ==
are only used when the variables contain numbers?
ANS:
=
and ==
are for string comparisons-eq
is for numeric comparisons-eq
is in the same family as -lt
, -le
, -gt
, -ge
, and -ne
==
is specific to bash (not present in sh (Bourne shell), ...). Using POSIX =
is preferred for compatibility. In bash the two are equivalent, and in sh =
is the only one that will work.
$ a=foo
$ [ "$a" = foo ]; echo "$?" # POSIX sh
0
$ [ "$a" == foo ]; echo "$?" # bash-specific
0
$ [ "$a" -eq foo ]; echo "$?" # wrong
-bash: [: foo: integer expression expected
2
(Note: make sure to quote the variable expansions. Do not leave out the double-quotes above.)
If you're writing a #!/bin/bash
script then I recommend using [[ instead. The double square-brackets [[...]]
form has more features, a more natural syntax, and fewer gotchas that will trip you up. For example, double quotes are no longer required around $a
:
$ [[ $a == foo ]]; echo "$?" # bash-specific
0
See also:
ref:bash - Shell equality operators (=, ==, -eq) - Stack Overflow