Shell – When to Use eq vs = vs == in Test Commands

shelltest

When should I use -eq vs = vs ==

e.g.

[[ $num -eq 0 ]]

[[ $num = 'zzz' ]]

I've observed a pattern of using -eq (and -ne, etc.) for numbers and = for strings. Is there a reason for this and when should I use ==

Best Answer

Because that's the definition for those operands. From POSIX test documentation, OPERANDS section:

s1 = s2

True if the strings s1 and s2 are identical; otherwise, false.

...

n1 -eq n2

True if the integers n1 and n2 are algebraically equal; otherwise, false.

== is not defined by POSIX, it's an extension of bash, derived from ksh. You shouldn't use == when you want portability. From bash documentation - Bash Conditional Expressions:

string1 == string2

string1 = string2

True if the strings are equal. ‘=’ should be used with the test command for POSIX conformance.

Related Question