1

I can see some article like this where it is mentioned that "-eq" is used to compare the integers, but this doesn't say that we can't use "==" for comparing the integers.

I verified this on bash shell locally and "==" is working fine. So can anyone let me help to understand which is better option to use, if "-eq" then why ?

Amit Sharma
  • 1,987
  • 2
  • 18
  • 29
  • Even for strings, `==` is not best practice inside `[ ]`; the POSIX sh standard specifies only `=`. Bash supports `==`, but this is an extension, and scripts using it may not be compatible with all other POSIX shells. – Charles Duffy Oct 19 '15 at 05:38
  • @CharlesDuffy so is `==` a "bashism" ? – amdixon Oct 19 '15 at 05:38

2 Answers2

5

To compare integers, use -eq. The difference is that == compares string value while -eq compares numeric value. Here is an example where they yield different results:

$ [ 03 = 3 ] ; echo $?
1
$ [ 03 -eq 3 ] ; echo $?
0

It is the same using [[:

$ [[ 03 == 3 ]] ; echo $?
1
$ [[ 03 -eq 3 ]] ; echo $?
0

As a number, 03 is equal to 3. But, as a string 03 and 3 are different.

Summary:  To compare numeric values for equality, use -eq

John1024
  • 109,961
  • 14
  • 137
  • 171
  • BTW -- I found it necessary to add my own answer for only a few reasons: Lack of mention of math contexts (in which case `==` is correct), and the implication that `==` is best practice in `[[ ]]` even for strings (whereas it leads to POSIX-incompliant habits when using `[ ]`). – Charles Duffy Oct 19 '15 at 05:40
2

It depends on the context. In a math context (which is preferable if you're writing your scripts specifically for bash), use ==.

(( foo == 3 ))     ## foo = 3 would be an assignment here, and foo -eq 3 an error

A math context is also present in other situations -- for instance, indexing into a non-associative array, making == preferred but -eq illegal in the below contrieved example:

foo=( yes no )
bar=3
echo "${foo[bar == 3 ? 0 : 1]}" # echoes "yes"

In [[ ]], use -eq.

[[ $foo -eq 3 ]]   ## $foo = 3 would be a string comparison here; $foo == 3 is a synonym,
                   ## but bad finger-memory to have if one wants to write POSIX code
                   ## elsewhere.

In [ ], use -eq -- and also quote:

[ "$foo" -eq 3 ]   ## = would be a valid string comparison here; == would be a
                   ## POSIX-incompatible string comparison here; -eq is correct.
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441