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?
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?
As for your main question: it is a duplicate of: Is [[ ]] preferable over [ ] in bash scripts?
[ ... ]
and [[ ... ]]
in this answer of mine.[[ ... ]]
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.
[[ ... ]]
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
[ ... ]
(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 [ ... ]
).
[[ ... ]]
, regular expression-matching operator =~
is available - see Bash Conditional ConstructsIn 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