Bash =~: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 16: Line 16:
* The use of [[...]] is required.
* The use of [[...]] is required.
* ''DO NOT use double quotes when specifying the regular expression, just specify the regex literal directly.''
* ''DO NOT use double quotes when specifying the regular expression, just specify the regex literal directly.''
* If the regular expression contains spaces, use single quotes to denote space:
<syntaxhighlight lang='bash'>
if [["something" =~ ${regex}' ' ]]; then ...
</syntaxhighlight>
* Variable substitution works for both the string to be matched and the regular expression. When using a variable to specify the regular expression, do not enclose the variable in quotes, use it directly as in the example below:
<syntaxhighlight lang='bash'>
if [[ "${var_containing_string_to_be_matched_against_regex}" =~ ${var_containing_regex} ]]; then ...
</syntaxhighlight>

Revision as of 20:36, 20 September 2019

Internal

Overview

The string to the right of the = ̃ operator is considered an extended regular expression and matched against the string to the left of the operator. The rules governing the extended regular expression are described in regex(3).

if [["string_to_be_matched_against_regex" =~ regex ]]; then
  # match 
else
  # no match 
fi

Usage is subject to the following constraints:

  • The use of [[...]] is required.
  • DO NOT use double quotes when specifying the regular expression, just specify the regex literal directly.
  • If the regular expression contains spaces, use single quotes to denote space:
if [["something" =~ ${regex}' ' ]]; then ...
  • Variable substitution works for both the string to be matched and the regular expression. When using a variable to specify the regular expression, do not enclose the variable in quotes, use it directly as in the example below:
if [[ "${var_containing_string_to_be_matched_against_regex}" =~ ${var_containing_regex} ]]; then ...