Jonhnny Weslley
Jonhnny Weslley

Reputation: 1080

Bash script if statements

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

Upvotes: 14

Views: 3583

Answers (5)

user unknown
user unknown

Reputation: 36229

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 from a file named "4" - redirecting stdin < The same for > and stdout.

Upvotes: 0

bashfu
bashfu

Reputation: 1

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

Upvotes: 0

Philipp
Philipp

Reputation: 49802

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

Upvotes: 2

mgv
mgv

Reputation: 8484

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.

Upvotes: 8

Chris Dodd
Chris Dodd

Reputation: 126203

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

Upvotes: 1

Related Questions