🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Double Brackets

Double brackets are the modern form of a Bash test. They add pattern matching and simpler joining inside one test.

A Modern Test

Double brackets hold the whole test. The equals sign still compares two strings.

name="Ada"
if [[ $name = "Ada" ]]; then
  echo "Hello, Ada"
fi

Joining Inside

The operators && and || sit inside the brackets here. No extra bracket pairs are needed.

age=30
if [[ $age -ge 18 && $age -lt 65 ]]; then
  echo "30 is in the working age range"
fi
if [[ $age -lt 18 || $age -ge 65 ]]; then
  echo "30 is in the other range"
else
  echo "30 is not in the other range"
fi

Matching a Pattern

With == the right side can hold a pattern. The star in A* matches the rest of the name.

name="Ada"
if [[ $name == A* ]]; then
  echo "Ada starts with A"
fi
if [[ $name == B* ]]; then
  echo "Ada starts with B"
else
  echo "Ada does not start with B"
fi

Example

city="New York"
if [[ $city = "New York" ]]; then
  echo "The city is New York"
fi
if [[ $city == New* && $city != "New Orleans" ]]; then
  echo "It is New York, not New Orleans"
fi

Key points

  • Double brackets start with [[ and end with ]].
  • Variables inside need no protection from word splitting.
  • The operators && and || work inside the brackets.
  • The operator == can match a text pattern.
  • A star in a pattern matches any characters.
  • Number operators like -ge work as before.

In this example, the unquoted variable holds a value with a space. Double brackets keep it as one value, and the pattern test passes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What can == do inside double brackets that a plain test cannot?