← Back to Bash Course | Chapter 7: String Manipulation | Lesson 5 of 10

[[ ]] Extended Test

The double-bracket test is like a smarter version of the quiz question: it copes with empty answers, matches patterns and does not get confused by spaces in your words.

In this page:

  1. [[ ]] Extended Test
Syntax
bash
[[ $string =~ regex ]]
[[ $string == pattern* ]]
[[ condition1 && condition2 ]]

[[ ]] Extended Test

[[ ]] is Bash's extended conditional syntax, supporting pattern matching, regex with =~, and safer handling of unquoted variables than [ ].

It doesn't word-split or glob-expand its operands, avoiding many of [ ]'s footguns. Modern Bash scripts generally prefer [[ ]] over [ ] when portability to POSIX sh isn't required.

Note: [[ $str =~ ^[0-9]+$ ]] tests whether a string matches a regular expression — [ ] can't do this.

Example: [[ ]] Extended Test

bash
#!/bin/bash
value="12345"

if [[ $value =~ ^[0-9]+$ ]]; then
    echo "$value is numeric"
else
    echo "$value is not numeric"
fi
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Quoting the pattern on the right of =~, which makes it a plain string instead of a regex.
  2. Using [[ ]] in a script that runs with sh, where it may not exist.
  3. Expecting && and || to work inside [ ], when they work in [[ ]].

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.