3

Is there a difference between the two code snippets below

    if [[ $a == "1" ]];then
       echo $a

and

    if [ $a == "1" ];then
       echo $a

Also, is there a difference when I use -eq in place of == in the above snippet?

mklement0
  • 382,024
  • 64
  • 607
  • 775

2 Answers2

4
  • As for your main question: it is a duplicate of: Is [[ ]] preferable over [ ] in bash scripts?

    • You can also find a (hopefully) comprehensive discussion of the differences between [ ... ] and [[ ... ]] in this answer of mine.
      In short: [[ ... ]] is parsed more like you'd expect in a regular programming language, and it implements many useful extensions, but it is not POSIX-compliant.
  • As for "is there a difference when I use -eq in place of ==?":

    • = and ==, its Bash alternative, perform string comparison.

      • Additionally, inside [[ ... ]] only, if the RHS of = or == is unquoted, it is interpreted as a glob-style pattern to match the LHS against; contrast [[ 'a' == '*' ]] && echo match with [[ 'a' == * ]] && echo match
      • Note that if you use [ ... ] (rather than [[ ... ]]) for POSIX compliance (portable use with /bin/sh), you should only use =, not ==; while Bash accepts == inside [ ... ] too, other shells don't.
    • -eq performs integer comparison

    • Other string/numeric operator pairs exist (e.g., -lt for numeric less-than vs. < for alphabetical (string) less-than, based on textual sort order).

  • Bash Conditional Expressions lists all operators you can use inside [ ... ] and [[ ... ]] (and also with test, which is effectively an alias of [ ... ]).

Community
  • 1
  • 1
mklement0
  • 382,024
  • 64
  • 607
  • 775
2

In bash, numeric comparison is handled differently than string comparison

For numbers,

$var1 -eq $var2   // =
$var1 -gt $var2   // >
$var1 -ge $var2   // >=
$var1 -lt $var2   // <
$var1 -le $var2   // <=
$var1 -ne $var2   // !=

For strings

$str1 = $str2   // they are equal
str1 != str2    // not equal
str             // Returns True if str is not null.
-n str          // Returns True if the length of str is greater than zero.
-z str          // Returns True if the length of str is equal to zero.

Note that == is the same as =

Also note that the == operates differently in a double bracket comparison (this is where your [ condition ] vs [[ condition ]] question comes in) when doing pattern matching. These comparisons/operators all all explained at http://www.tldp.org/LDP/abs/html/comparison-ops.html

ivanivan
  • 2,155
  • 2
  • 10
  • 11
  • ++ for a helpful overview, though I suggest adding string operators `<` and `>` for symmetry (even though they're used much less frequently). For convenience, here is a direct link to the explanation of the difference between `[ … ]` and `[[ … ]]` from the page you link to: http://www.tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS – mklement0 Dec 10 '16 at 14:25