开发者

bash/sh if statement syntax

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 s开发者_StackOverflowtatements, 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 ]]


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


[ 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.


I recommend case/esac.

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

No fretting about different syntax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜