More Bash answers

by Danny
Published 2 min read

Learn the difference between [ and [[ in Bash, when to use each, and how to write if statements for strings, numbers, files and patterns without quoting bugs.

The short answer

#

In a Bash script, use [[ ... ]] for tests. It is a Bash keyword, so it does not split words or expand globs inside the brackets, and it supports &&, ||, pattern matching and regular expressions. Use [ ... ] only when the script must run under plain sh. Always leave a space after the opening bracket and before the closing one.


_10
name="Ada Lovelace"
_10
_10
if [[ $name == "Ada Lovelace" ]]; then
_10
echo "Hello, Ada"
_10
fi
_10
_10
# POSIX version for /bin/sh: quote everything
_10
if [ "$name" = "Ada Lovelace" ]; then
_10
echo "Hello, Ada"
_10
fi

Why it happens

#

if in Bash does not take a condition the way it does in JavaScript. It runs a command and checks its exit status: zero means true, anything else means false. [ is an ordinary command (also called test), and ] is just its last argument. That is why the spaces matter: ["$a" = "b"] asks the shell to run a command literally named ["value", which fails with "command not found".

Because [ is a normal command, the shell expands its arguments before it runs. An unquoted variable that is empty disappears entirely, and one that contains spaces becomes several arguments. You get errors such as "unary operator expected" or "too many arguments".

[[ is part of Bash's syntax, so the shell parses what is inside it specially. Variables are not split or globbed, so [[ $name == "Ada Lovelace" ]] works even without quotes on the left. It also lets you combine conditions with && and || inside the brackets, which [ cannot do safely.

How to fix it

#

Use [[ for strings and patterns


_11
file="report.csv"
_11
_11
if [[ -z $file ]]; then
_11
echo "No file given"
_11
elif [[ $file == *.csv ]]; then
_11
echo "CSV file"
_11
elif [[ $file =~ ^report-([0-9]+)\.txt$ ]]; then
_11
echo "Report number ${BASH_REMATCH[1]}"
_11
else
_11
echo "Something else"
_11
fi

On the right-hand side of ==, an unquoted value is treated as a glob pattern. Quote it when you want a literal comparison: [[ $a == "$b" ]]. For =~, keep the regex unquoted, or store it in a variable first, because quoting turns it into a plain string match.

Use (( )) for numbers

String comparison and number comparison are different operators. For integers, the arithmetic form is the easiest to read.


_10
count=12
_10
_10
if (( count > 10 )); then
_10
echo "More than ten"
_10
fi
_10
_10
# Equivalent test operators, which also work in [ ]
_10
if [[ $count -gt 10 ]]; then
_10
echo "More than ten"
_10
fi

The test operators are -eq, -ne, -lt, -le, -gt and -ge. Inside [ the symbols for less than and greater than are redirections, so never use them for numbers there.

Test files with the same brackets


_10
if [[ -f config.json && -r config.json ]]; then
_10
echo "Config exists and is readable"
_10
fi
_10
_10
if [[ ! -d build ]]; then
_10
mkdir build
_10
fi

Use [ with quotes when you need POSIX sh

If the script starts with #!/bin/sh, or runs in a minimal container where sh is dash or BusyBox, [[ is not available. Quote every variable and combine tests with separate brackets.


_10
#!/bin/sh
_10
if [ -n "$HOME" ] && [ -d "$HOME" ]; then
_10
echo "Home is set"
_10
fi

Use = for string equality in [. The == form is a Bash extension.

Skip the brackets when you are testing a command

You do not need brackets to check whether a command worked. Put the command straight after if.


_10
if grep -q "TODO" notes.txt; then
_10
echo "Found a TODO"
_10
fi

Common pitfalls

#
  • Missing spaces. if [[$x == 1]] fails. The brackets need a space on both sides.
  • Comparing numbers as strings. [[ 10 == 10.0 ]] is false and [[ 9 > 10 ]] is true, because those operators compare text. Use (( )) or -gt.
  • Forgetting then or fi****. Put then on the next line or after a semicolon: if ...; then.
  • Using -a and -o inside [****. They are ambiguous and marked obsolescent in POSIX. Use [ a ] && [ b ] or [[ a && b ]].
  • Running a Bash script with sh****. sh script.sh ignores the Bash shebang, so [[ may fail with "not found". Run it as ./script.sh or bash script.sh.
#

Was this resource helpful?