tags:

views:

811

answers:

3

A co-worker claimed recently in a code review that the [[ ]] construct is to be preferred over [ ] in constructs like

if [ "`id -nu`" = "$someuser" ] ; then 
     echo "I love you madly, $someuser"
fi

He couldn't provide a rationale. Is there one?

+3  A: 

[[ ]] has more features - I suggest you take a look at the Advanced Bash Scripting Guide for more info.

anon
+4  A: 

From Which comparator, test, bracket, or double bracket, is fastest? (http://bashcurescancer.com)

The double bracket is a “compound command” where as test and the single bracket are shell built-ins (and in actuality are the same command). Thus, the single bracket and double bracket execute different code.

The test and single bracket are the most portable as they exist as separate and external commands. However, if your using any remotely modern version of BASH, the double bracket is supported.

f3lix
+15  A: 

[[ has less surprises and is generally safer to use. But it is not portable - Posix doesn't specify what it does and only some shells support it (beside bash, i heard ksh supports it too). For example, you can do

[[ -e $b ]]

To test whether a file exists. But with [, you have to quote $b, because it splits the argument and expands things like "a*" (where [[ takes it literally). That has also todo with how [ can be an external program and receives its argument just normally like every other program (although it can also be a builtin, but then it still has not this specialhandling).

[[ also has some other nice features, like regular expression matching and operators like they are known in C like languages. Here is a good page about it: What is the difference between test, [ and [[ ? and Bash Tests

Johannes Schaub - litb
Good info. Thanks.
Leonard
Considering that bash is everywhere these days, I tend to think it's pretty damn portable. The only common exception for me is on busybox platforms - but you'd probably want to make a special effort for it anyways, given the hardware that it runs on.
guns