Skip to content
Vidar Holen edited this page Oct 4, 2015 · 6 revisions

Don't quote rhs of =~, it'll match literally rather than as a regex.

Problematic code:

[[ $foo =~ "^fo+bar$" ]]

Correct code:

[[ $foo =~ ^fo+bar$ ]]

Rationale:

Quotes on the right hand side of =~ can be used to match literally, so that [[ $1 =~ ^"$2".* ]] works even if $2 contains regex metacharacters. This mirrors the behavior of globs, [[ $1 = "$2"* ]].

This also means that the problematic code tries to match literal carets and plus signs instead of interpreting them as regular expression matchers. To match as a regex, it must be unquoted.

Exceptions:

If you do want to match literally just to do a plain substring search, e.g. [[ $foo =~ "bar" ]], you could ignore this message, but consider using a more canonical glob match instead: [[ $foo = *"bar"* ]].

Compatibility:

  • In Bash 3.2 and newer with shopt compat31 disabled (the default), quoted patterns are literal whereas unquoted patterns are parsed for regex metacharacters.
  • In Bash 3.2 and newer with shopt compat31 enabled, quoted and unquoted patterns match identically.
  • In Bash 3.1 quoted and unquoted patterns match identically.

See http://stackoverflow.com/questions/218156/bash-regex-with-quotes

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally