7

In various guides and scripts I come across people tend to use different syntax of if statements. What's the difference and what are best practices? I believe all the following statements, and many more variants, will return true:

bar="foo"
if [ "foo" = "foo" ]
if [[ "foo" == $bar ]]
if [ "foo" = "$bar" ]
if [[ "foo" = "$bar" ]]
if [[ "foo" -eq $bar ]]
2

3 Answers 3

5

As I understand it

= expects strings

-eq expects integers

"$bar" is for literal matches, i.e. z* may expand but "z*" will literally match the wildcard char.

The difference between [] and [[]] is that in the latter word splitting and path name expansion are not done, but are in the former.

Plus [[]] allows the additional operators :

&& (AND), || (OR), > (String1 lexically greater than String2), < (String1 lexically less than String2)

The == comparison operator behaves differently within a double-brackets test than within single brackets.

[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).

[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

[ $a == z* ] # File globbing and word splitting take place.

[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).

Check out http://tldp.org/LDP/abs/html/comparison-ops.html for more info

Sign up to request clarification or add additional context in comments.

1 Comment

Minor correction/clarification: = and == do exactly the same thing (i.e. they both do pattern matching within [[ ]]) except that some implementations of [ don't support ==. Basically, the only reason to use == is that it's familiar from other languages. Also, [ does support string comparisons with < and >, you just have to escape them or they'll be parsed as I/O redirections: [ string1 \< string2 ] for example.
3

[ is a bash builtin, [[ is a bash keyword. Best practice is to always use [[ if the script doesn't have to be compatible with other shells (e.g., if it starts with #!/bin/bash), and use [ only for compatibility with the Bourne shell. See http://mywiki.wooledge.org/BashFAQ/031.

Comments

2

I recommend case/esac.

case "$foo" in
  "bar" ) echo "bar";;
  *) echo "not equal";;
esac

No fretting about different syntax.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.