In Bash script, what is the differe开发者_如何学运维nce between the following snippets?
1) Using single brackets:
if [ "$1" = VALUE ] ; then
# code
fi
2) Using double brackets:
if [[ "$1" = VALUE ]] ; then
# code
fi
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.
[
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.
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
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.)
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.
精彩评论