Use Double Brackets Instead Of Single Bracket For Tests In Bash
2 min readNov 24, 2021
The aim of this pageđź“ťis to explain and list the advantages of using [[
conditional expressions instead of [
aka test
builtin in bash. Some explanation first, then the three benefits from an SO thread.
- historically, before any conditional expressions, there was an only command called
test
test
is still there for compatibility with othersh
shellstest
is also known as[
— single square bracket instead of two square bracket- you can encounter
[
in the wild also in bash scripts a lot [
is a regular shell command- therefore there are lots of tiny pitfalls for the old
test
command or[
- beware that
[
exists but don't use it - → rule: use
[
only if you need a script that has to run on non-bash shell machines - Make sure you have the
#!/bin/bash
shebang line for your script if you use double brackets. [[
originates from bash and is generally treated as bash-specific (don't know about other shells there may be adoption)[[
is easier[[
is not a command[[
is a bash extension- it has a dedicated syntax and it is parsed in a special way
- e.g. no need to quote variables
- write
help test
to get info on essentials - write
help [[
for bash specific operations - from my experience, however, I keep seeing
[
also in bash-only scripts so the the knowledge of differences is still relevant
1. logical operators
- can use
&&
and||
operators for boolean tests - can use
<
and>
for string comparisons. [
cannot do this because it is a regular command&&
,||
,<
, and>
are not passed to regular commands as command-line arguments
2. regex
- can use
=~
operator for regex matches - capture groups are stored in
BASH_REMATCH
var
if [[ $answer =~ ^y(es)?$ ]]
3. globbing
- can use pattern matching with wildcards
if [[ $ANSWER = y* ]]