Jonathan Matthews Jonathan Matthews - 4 months ago 26
Bash Question

Match a single character in a Bash regular expression

For some reason, the following regular expression match doesn't seem to be working.

string="#Hello world";
[[ "$string" =~ 'ello' ]] && echo "matches";
[[ "$string" =~ 'el.o' ]] && echo "matches";

The first command succeeds (as expected), but the second one does not.

Shouldn't that period be treated by the regular expression as a single character?


Quoting the period causes it to be treated as a literal character, not a regular-expression metacharacter. Best practice if you want to quote the entire regular expression is to do so in a variable, where regular expression matching rules aren't in effect, then expand the parameter unquoted (which is safe to do inside [[ ... ]]).

[[ "$string" =~ $regex ]] && echo "matches"