42

I am trying to match on the presence of a word in a list before adding that word again (to avoid duplicates). I am using bash 4.2.24 and am trying the below:

[[  $foo =~ \bmyword\b ]]

also

[[  $foo =~ \<myword\> ]]

However, neither seem to work. They are mentioned in the bash docs example: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_04_01.html.

I presume I am doing something wrong but I am not sure what.

codeforester
  • 39,467
  • 16
  • 112
  • 140
starfry
  • 9,273
  • 7
  • 66
  • 96
  • 7
    As an aside: the behavior of bash's `=~` operator is _platform-dependent_, because the host platform's regex libraries are used. Thus, for instance, even with the workaround in the accepted answer, `\b` and `\<` / `\>` won't work on BSD-like systems such as OSX. Conversely, OSX supports `[[:\<:]]` and `[[:\>:]]`, which won't work on Linux. – mklement0 Mar 28 '15 at 15:47
  • Use double backslashes (\\) for regex for example in `[ string =~ pattern]` or in `grep` – Shayan Apr 08 '20 at 12:27
  • There are two topics discussed in the answers here. The first is the use of a regex literal, and the second is platform-dependence of word boundary tokens. For the first topic, there's a more focused discussion at https://stackoverflow.com/q/218156. – Near Privman Aug 11 '22 at 13:39

8 Answers8

64

tl;dr

  • To be safe, do not use a regex literal with =~.
    Instead, use:

  • Whether \b and \< / \> are supported at all depends on the host platform, not Bash:

    • they DO work on Linux,
    • but NOT on BSD-based platforms such as macOS; there, use [[:<:]] and [[:>:]] instead, which, in the context of an unquoted regex literal, must be escaped as [[:\<:]] and [[:\>:]]; the following works as expected, but only on BSD/macOS:
      • [[ ' myword ' =~ [[:\<:]]myword[[:\>:]] ]] && echo YES # OK
  • The problem wouldn't arise - on any platform - if you limited your regex to the constructs in the POSIX ERE (extended regular expression) specification.

    • Unfortunately, POSIX EREs do not support word-boundary assertions, though you can emulate them - see the last section.

    • As on macOS, no \-prefixed constructs are supported, so that handy character-class shortcuts such as \s and \w aren't available either.

    • However, the up-side is that such ERE-compliant regexes are then portable (work on both Linux and macOS, for instance)

=~ is the rare case (the only case?) of a built-in Bash feature whose behavior is platform-dependent: It uses the regex libraries of the platform it is running on, resulting in different regex flavors on different platforms.

Thus, it is generally non-trivial and requires extra care to write portable code that uses the =~ operator. Sticking with POSIX EREs is the only robust approach, which means that you have to work around their limitations - see bottom section.

If you want to know more, read on.


On Bash v3.2+ (unless the compat31 shopt option is set), the RHS (right-hand side operand) of the =~ operator must be unquoted in order to be recognized as a regex (if you quote the right operand, =~ performs regular string comparison instead).

More accurately, at least the special regex characters and sequences must be unquoted, so it's OK and useful to quote those substrings that should be taken literally; e.g., [[ '*' =~ ^'*' ]] matches, because ^ is unquoted and thus correctly recognized as the start-of-string anchor, whereas *, which is normally a special regex char, matches literally due to the quoting.

However, there appears to be a design limitation in (at least) bash 3.x that prevents use of \-prefixed regex constructs (e.g., \<, \>, \b, \s, \w, ...) in a literal =~ RHS; the limitation affects Linux, whereas BSD/macOS versions are not affected, due to fundamentally not supporting any \-prefixed regex constructs:

# Linux only:
# PROBLEM (see details further below): 
#   Seen by the regex engine as: <word>
#   The shell eats the '\' before the regex engine sees them.
[[ ' word ' =~ \<word\> ]] && echo MATCHES # !! DOES NOT MATCH
#   Causes syntax error, because the shell considers the < unquoted.
#   If you used \\bword\\b, the regex engine would see that as-is.
[[ ' word ' =~ \\<word\\> ]] && echo MATCHES # !! BREAKS
#   Using the usual quoting rules doesn't work either:
#   Seen by the regex engine as: \\<word\\> instead of \<word\>
[[ ' word ' =~ \\\<word\\\> ]] && echo MATCHES # !! DOES NOT MATCH

# WORKAROUNDS
  # Aux. viarable.  
re='\<word\>'; [[ ' word ' =~ $re ]] && echo MATCHES # OK
  # Command substitution
[[ ' word ' =~ $(printf %s '\<word\>') ]] && echo MATCHES # OK

  # Change option compat31, which then allows use of '...' as the RHS
  # CAVEAT: Stays in effect until you reset it, may have other side effects.
  #         Using (...) around  the command confines the effect to a subshell.
(shopt -s compat31; [[ ' word ' =~ '\<word\>' ]] && echo MATCHES) # OK

The problem:

Tip of the hat to Fólkvangr for his input.

A literal RHS of =~ is by design parsed differently than unquoted tokens as arguments, in an attempt to allow the user to focus on escaping characters just for the regex, without also having to worry about the usual shell escaping rules in unquoted tokens.

For instance,

[[ 'a[b' =~ a\[b ]] && echo MATCHES  # OK

matches, because the \ is _passed through to the regex engine (that is, the regex engine too sees literal a\[b), whereas if you used the same unquoted token as a regular argument, the usual shell expansions applied to unquoted tokens would "eat" the \, because it is interpreted as a shell escape character:

$ printf %s a\[b
a[b  # '\' was removed by the shell.

However, in the context of =~ this exceptional passing through of \ is only applied before characters that are regex metacharacters by themselves, as defined by the ERE (extended regular expressions) POSIX specification (in order to escape them for the regex, so that they're treated as literals:
\ ^ $ [ { . ? * + ( ) |
Conversely, these regex metacharacters may exceptionally be used unquoted - and indeed must be left unquoted to have their special regex meaning - even though most of them normally require \-escaping in unquoted tokens to prevent the shell from interpreting them.
Yet, a subset of the shell metacharacters do still need escaping, for the shell's sake, so as not to break the syntax of the [[ ... ]] conditional:
& ; < > space
Since these characters aren't also regex metacharacters, there is no need to also support escaping them on the regex side, so that, for instance, the regex engine seeing \& in the RHS as just & works fine.

For any other character preceded by \, the shell removes the \ before sending the string to the regex engine (as it does during normal shell expansion), which is unfortunate, because then even characters that the shell doesn't consider special cannot be passed as \<char> to the regex engine, because the shell invariably passes them as just <char>.
E.g, \b is invariably seen as just b by the regex engine.

It is therefore currently impossible to use a (by definition non-POSIX) regex construct in the form \<char> (e.g., \<, \>, \b, \s, \w, \d, ...) in a literal, unquoted =~ RHS, because no form of escaping can ensure that these constructs are seen by the regex engine as such, after parsing by the shell:

Since neither <, >, nor b are regex metacharacters, the shell removes the \ from \<, \>, \b (as happens in regular shell expansion). Therefore, passing \<word\>, for instance, makes the regex engine see <word>, which is not the intent:

  • [[ '<word>' =~ \<word\> ]] && echo YES matches, because the regex engine sees <word>.
  • [[ 'boo' =~ ^\boo ]] && echo YES matches, because the regex engine sees ^boo.

Trying \\<word\\> breaks the command, because the shell treats each \\ as an escaped \, which means that metacharacter < is then considered unquoted, causing a syntax error:

  • [[ ' word ' =~ \\<word\\> ]] && echo YES causes a syntax error.
  • This wouldn't happen with \\b, but \\b is passed through (due to the \ preceding a regex metachar, \), which also doesn't work:
    • [[ '\boo' =~ ^\\boo ]] && echo YES matches, because the regex engine sees \\boo, which matches literal \boo.

Trying \\\<word\\\> - which by normal shell expansion rules results in \<word\> (try printf %s \\\<word\\\>) - also doesn't work:

  • What happens is that the shell eats the \ in \< (ditto for \b and other \-prefixed sequences), and then passes the preceding \\ through to the regex engine as-is (again, because \ is preserved before a regex metachar):

  • [[ ' \<word\> ' =~ \\\<word\\\> ]] && echo YES matches, because the regex engine sees \\<word\\>, which matches literal \<word\>.

In short:

  • Bash's parsing of =~ RHS literals was designed with single-character regex metacharacters in mind, and does not support multi-character constructs that start with \, such as \<.

    • Because POSIX EREs support no such constructs, =~ works as designed if you limit yourself to such regexes.

    • However, even within this constraint the design is somewhat awkward, due to the need to mix regex-related and shell-related \-escaping (quoting).

    • Fólkvangr found the official design rationale in the Bash FAQ here, which, however, neither addresses said awkwardness nor the lack of support for (invariably non-POSIX) \<char> regex constructs; it does mention using an aux. variable as a workaround, however, although only with respect to making it easier to represent whitespace.

  • All these parsing problems go away if the string that the regex engine should see is provided via a variable or via the output from a command substitution, as demonstrated above.


Optional reading: A portable emulation of word-boundary assertions with POSIX-compliant EREs (extended regular expressions):

  • (^|[^[:alnum:]_]) instead of \< / [[:<:]]

  • ([^[:alnum:]_]|$) instead of \> / [[:>:]]

Note: \b can't be emulated with a SINGLE expression - use the above in the appropriate places.

The potential caveat is that the above expressions will also capture the non-word character being matched, whereas true assertions such as \< / [[:<:]] and do not.

$foo = 'myword'
[[ $foo =~ (^|[^[:alnum:]_])myword([^[:alnum:]_]|$) ]] && echo YES

The above matches, as expected.

John Mellor
  • 12,572
  • 4
  • 46
  • 35
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 2
    This should be the accepted answer as it applies across POSIX systems. – miguelmorin Jun 10 '19 at 16:03
  • 1
    I've spent about an hour looking for this answer. Should be the solution! Thank you. – Joe Sadoski Aug 31 '20 at 22:18
  • 1
    Incredibly through and well working answer. Should be the accepted answer. Thanks for this! – Chris Nagai Apr 17 '22 at 21:18
  • Glad to hear it, @ChrisNagai; my pleasure. I appreciate the nice feedback. – mklement0 Apr 17 '22 at 21:31
  • `[[:\<:]]` does not work with Bash 5.2 on MacOS 13.2. `[[:<:]]` does work. With zsh `[[:\<:]]` is an invalid character class. `[[:<:]]` works. – dawg Feb 04 '23 at 17:31
  • 1
    @dawg, `[[ ' myword ' =~ [[:\<:]]myword[[:\>:]] ]] && echo YES` still works for me, both with a (Homebrew-installed) Bash v5.2.15(1), and with the system `zsh` (`/bin/zsh`, v5.8.1 as of macOS 13.1) – mklement0 Feb 04 '23 at 21:30
  • @mklement0: Try in a variable. With `[[ ' myword ' =~ $re ]] && echo MATCH || echo 'NO MATCH'` if you have `re='[[:<:]]myword'` it works but `re='[[:\<:]]myword'` does not. With the literal the opposite is true! – dawg Feb 04 '23 at 22:22
  • @dawg, yes, the use of ``\`` escaping is only required in _literal_, (of necessity) _unquoted_ use. So the variable-based equivalent of the command in my previous comment is: ``re='[[:<:]]myword[[:>:]]'; [[ ' myword ' =~ $re ]] && echo YES``. Note that this distinction isn't specific to the `=~` operator. – mklement0 Feb 04 '23 at 22:51
34

Yes, all the listed regex extensions are supported but you'll have better luck putting the pattern in a variable before using it. Try this:

re=\\bmyword\\b
[[ $foo =~ $re ]]

Digging around I found this question, whose answers seems to explain why the behaviour changes when the regex is written inline as in your example.

Editor's note: The linked question does not explain the OP's problem; it merely explains how starting with Bash version 3.2 regexes (or at least the special regex chars.) must by default be unquoted to be treated as such - which is exactly what the OP attempted.
However, the workarounds in this answer are effective.

You'll probably have to rewrite your tests so as to use a temporary variable for your regexes, or use the 3.1 compatibility mode:

shopt -s compat31
mklement0
  • 382,024
  • 64
  • 607
  • 775
Eduardo Ivanec
  • 11,668
  • 2
  • 39
  • 42
  • 5
    +1. Alternatively, you can use command substitution: `[[ $foo =~ $(echo '\') ]]`. It's still annoyingly verbose, but at least doesn't require a stray variable. – ruakh Mar 20 '12 at 22:59
  • Note that the `$(echo ..)` version comes with a performance penalty, as compared to the local variable, which might be a disadvantage in some cases. – Near Privman Aug 11 '22 at 12:05
10

Not exactly "\b", but for me more readable (and portable) than the other suggestions:

[[  $foo =~ (^| )myword($| ) ]]
Weidenrinde
  • 2,152
  • 1
  • 20
  • 21
5

The accepted answer focuses on using auxiliary variables to deal with the syntax oddities of regular expressions in Bash's [[ ... ]] expressions. Very good info.

However, the real answer is:

\b \< and \> do not work on OS X 10.11.5 (El Capitan) with bash version 4.3.42(1)-release (x86_64-apple-darwin15.0.0).

Instead, use [[:<:]] and [[:>:]].

Colin Fraizer
  • 532
  • 4
  • 14
  • 1
    there's a comment on the original question from @mklement0 that says this too. – starfry Jun 16 '16 at 16:09
  • Given that the question has no platform-specific tagging, the answer is: If you're on _macOS_ / a _BSD_ platform, you're not affected by the bug in the OP, because `\ `-prefixed constructs are fundamentally unavailable there (and to use the `[[:<:]]` and `[[:>:]]` alternatives there in an _unquoted_ `=~` RHS, you must escape them as `[[:\<:]]` and `[[:\>:]]`). On _Linux_, a Bash design flaw prevents the use of the available `\ `-prefixed constructs in (of necessity) unquoted `=~` RHS _literals_, and the accepted answer and others show effective workarounds. – mklement0 Dec 21 '18 at 20:01
4

Tangential to your question, but if you can use grep -E (or egrep, its effective, but obsolescent alias) in your script:

if grep -q -E "\b${myword}\b" <<<"$foo"; then

I ended up using this after flailing with bash's =~.

Note that while regex constructs \<, \>, and \b are not POSIX-compliant, both the BSD (macOS) and GNU (Linux) implementations of grep -E support them, which makes this approach widely usable in practice.

Small caveat (not an issue in the case at hand): By not using =~, you lose the ability to inspect capturing subexpressions (capture groups) via ${BASH_REMATCH[@]} later.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Ben Flynn
  • 18,524
  • 20
  • 97
  • 142
2

I've used the following to match word boundaries on older systems. The key is to wrap $foo with spaces since [^[:alpha:]] will not match words at the beginning or end of the list.

[[ " $foo " =~ [^[:alpha:]]myword[^[:alpha:]] ]]

Tweak the character class as needed based on the expected contents of myword, otherwise this may not be good solution.

Cole Tierney
  • 9,571
  • 1
  • 27
  • 35
1

This worked for me

bar='\<myword\>'
[[ $foo =~ $bar ]]
Zombo
  • 1
  • 62
  • 391
  • 407
  • Yes, but that's effectively the same as the accepted answer. On Linux, both `bar='\'` and `bar='\bmyword\b'` (or unquoted, as in the accepted answer, `bar=\\bmyword\\b`) work. – mklement0 Jul 14 '14 at 13:36
1

You can use grep, which is more portable than bash's regexp like this:

if echo $foo | grep -q '\<myword\>'; then 
    echo "MATCH"; 
else 
    echo "NO MATCH"; 
fi
  • `grep` itself is portable, but `\<` as a grep feature is **not** -- unless you can point to where the POSIX specification defines it? I see no references in http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html or http://pubs.opengroup.org/onlinepubs/9699919799.2008edition/utilities/grep.html – Charles Duffy Dec 21 '18 at 17:21
  • 1
    (And `echo $foo` introduces its own bugs; see [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo)). – Charles Duffy Dec 21 '18 at 17:23
  • @CharlesDuffy: Good point about `\<`, `\>` and `\b` not being part of POSIX, but both the BSD (macOS) and GNU `grep` (Linux) implementations support them, which makes this approach widely usable in practice. – mklement0 Dec 21 '18 at 20:14
  • Aside from the fragility of `echo $foo` (unquoted variable reference) that Charles points out, note that `grep` by default uses only _basic_ regular expressions (BREs), whereas `=~` uses _extended_ regular expressions (EREs); to make the `grep` command work more like the latter, use `grep -E -q ...` - but then you'll have duplicated [this preexisting answer](https://stackoverflow.com/a/19962581/45375). – mklement0 Dec 23 '18 at 18:46