1

What is the difference between [ test ] and [[ test ]] in bash? When is one more appropriate than the other and what does the ; at the end do?

if  [[ -z $DIRECTORY ]];
then
     DIRECTORY=html
fi

if [ ! -d "$DIRECTORY" ]; then
    echo installation directory "'${DIRECTORY}'" does not exist
    exit 1
fi
vfclists
  • 19,193
  • 21
  • 73
  • 92
  • 1
    possible duplicate of [bash: double or single bracket, parentheses, curly braces](http://stackoverflow.com/questions/2188199/bash-double-or-single-bracket-parentheses-curly-braces) and [What's the difference between \[ and \[\[ in bash?](http://stackoverflow.com/q/3427872/218196). – Felix Kling Jan 20 '13 at 14:14

3 Answers3

3

[[ is a bash keyword similar to (but more powerful than) the [ command. See http://mywiki.wooledge.org/BashFAQ/031 and http://mywiki.wooledge.org/BashGuide/TestsAndConditionals Unless you're writing for POSIX sh, we recommend [[.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

We usually use single square brackets when we:

  • Check something with files and want to use patterns (e.g. asterisk): if [ -L $file ]; then
  • Check artithmetic expressions: if [ $a -lt $b ]; then
  • Check something with strings and want to use " " and treat special characters as normal (e.g. asterisk): if [ -z "$string" ]; then

We usually double square brackets when we:

  • Want to use pattern with string (e.g. asterisk): if [[ "$string1" == *[sS]tring* ]]; then
  • Block patterns in file names (e.g. asterisk) e.g. we search file named *.sh: if [[ -a *.sh ]]; then
  • Want to use operators && and ||: if [[ $a == 3 || $b == 4]]; then
  • Don't want to put strings in " "
Adam Sznajder
  • 9,108
  • 4
  • 39
  • 60
  • 1
    You make a rather artificial distinction, since everything you list under single brackets can be done with double brackets. – chepner Jan 20 '13 at 15:39
  • Of course you're right. It's just wrote the way I remember when to use which brackets :) – Adam Sznajder Jan 20 '13 at 15:41
  • 1
    My point is, you don't *need* to use single brackets for any of those. Use single brackets if you are writing code that needs to be POSIX-compatible; use double brackets if your code only needs to run under `bash`. – chepner Jan 20 '13 at 15:42
0

[ is for shell, [[ is for bash.

For example :
Try [ $A -eq 1 ]: if $A is not set, it raise an error.
[[ $A -eq 1 ]] will works.

Zulu
  • 8,765
  • 9
  • 49
  • 56