
Note: the = operator in sh and bash is for string comparison. You will also get an error if one of the arguments is substituted with a value with whitespace with single brackets, while double brackets can deal with this.

This means they can react more tolerantly to ‘disappearing’ arguments: $ ] || echo "unequal" $ || echo "unequal"ĭouble brackets in bash are not a command but a part of the language syntax. You can prevent this error by quoting the variables (always a prudent solution). Note: in bash on macoS both test and [ are built-in commands, but as usual for built-in commands there are also executables /bin/test and /bin/[.Ī single bracket test will fail when one of its arguments is empty and gets substituted to nothing: $ a="abc" The single bracket $ [ -d Documents & echo "found docs" The second is much shorter, but as soon as the test or the command gets more complex you should revert to the longer syntax.Īlternatively, the ‘or’ operator || will only execute the following statement when the previous statement returns non-zero or fails: || echo "no docs" So you can use & to write simple if … then … clauses in a single line. The ‘and’ operator & will execute the following statement only if the preceding statement returns 0 (success). These are tedious to write in the interactive shell. In shell scripts you usually use tests in if or while clauses.

I go into detail on why to use bash over sh in this post: On the Shebang Side note on syntax Consistent behavior across platforms is the main point why sh is still around, so don’t use double brackets in sh (or use bash to use double brackets). Since sh on macOS is bash pretending to be sh, double brackets will still work with the wrong shebang, but then your script might break on other platforms where a different shell might be pretending to be sh. To use double brackets your shebang should be #!/bin/bash not #!/bin/sh. I also talked about this briefly in my MacSysAdmin session: Scripting Bash Double Brackets are a bashismĭouble brackets were originally introduced in ksh and later adopted by bash and other shells. In my recent post I mentioned in passing, that you should be using double brackets ] for tests in bash instead of single brackets.
