tags:

views:

107

answers:

5

In Bash script, what is the difference between the following snippets?

1) Using single brackets:

if [ "$1" = VALUE ] ; then
 # code
fi

2) Using double brackets:

if [[ "$1" = VALUE ]] ; then
 # code
fi
+7  A: 

The [[ ]] construct is the more versatile Bash version of [ ]. This is the extended test command, adopted from ksh88.

Using the [[ ... ]] test construct, rather than [ ... ] can prevent many logic errors in scripts. For example, the &&, ||, <, and > operators work within a [[ ]] test, despite giving an error within a [ ] construct.

More info on the Advanced Bash Scripting Guide.

In your snippets, there's no difference as you're not using any of the additional features.

mgv
+1  A: 

Using [[ supresses the normal wordsplitting and pathname expansion on the expression in the brackets. It also enables a number of addition operations, like pattern matching

Chris Dodd
+1  A: 

[ is a bash builtin, [[ is a keyword. See the bash FAQ. Beware: most bash scripts on the internet are crap (don't work with filenames with spaces, introduce hidden security holes, etc.), and bash is much more difficult to master than one might think. If you want to do bash programming, you should study at least the bash guide and the bash pitfalls.

Philipp
A: 

Just in case portability is needed:

For portability testing you can get the Bourne shell via the Heirloom project or:

http://freshmeat.net/projects/bournesh

(On Mac OS X, for example, /bin/sh is no pure Bourne shell.)

bashfu
A: 

which is also an external program, which doesn't mean that it isn't a builtin.

which [
/usr/bin/[

In single square brackets you have to use -lt for 'less than' alias < while else you could use <

if [ 3 -lt 4 ] ; then echo yes ; fi
yes
if [ 3 < 4 ] ; then echo yes ; fi
bash: 4: No such file or directory
if [[ 3 < 4 ]] ; then echo yes ; fi
yes
if [[ 3 -lt 4 ]] ; then echo yes ; fi
yes

4: No such file means, it tries to read form 4 - redirecting stdin < The same for > and stdout.

user unknown