Regular Expression : bash 3 vs bash 4 Regular Expression : bash 3 vs bash 4 shell shell

Regular Expression : bash 3 vs bash 4


In older versions of Bash (3.1), it was possible to use quotes around a regular expression in a test. In newer versions, the quotes are treated as part of the pattern, so the match fails.

The solution is to remove the quotes.


The recommended way to use regular expressions is this:

re='^testcase[0-9\.]*$'  # single quotes around variable[[ ${TESTCASE} =~ $re ]] # unquoted variable used in test

This syntax should work in all versions of bash that support regular expressions. The variable isn't strictly necessary but it improves readability. See the regular expressions section of Greg's wiki for more details.

Regarding the use of a variable (from the link above):

For cross-compatibility (to avoid having to escape parentheses, pipes and so on) use a variable to store your regex, e.g. re='^\*( >| *Applying |.*\.diff|.*\.patch)'; [[ $var =~ $re ]] This is much easier to maintain since you only write ERE syntax and avoid the need for shell-escaping, as well as being compatible with all 3.x BASH versions.

By the way, there's no need to escape the . inside the bracket expression.