2
votes

I'm trying to match a simple regex in a bash script. It behaves as expected with GNU bash, version 4.2.24(1)-release (x86_64-pc-linux-gnu) but does not with GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)

here is the code:


#!/bin/bash

line="[foo]"
[[ $line =~ ^\[.*\]$ ]] && echo "regex matched"
echo "value of \$? : " $?
echo "value of BASH_REMATCH : " $BASH_REMATCH
/bin/bash --version|grep "GNU bash"

here is the output with GNU bash, version 4.2.24(1)-release (x86_64-pc-linux-gnu)

regex matched
value of $? : 0
value of BASH_REMATCH : [foo]
GNU bash, version 4.2.24(1)-release (x86_64-pc-linux-gnu)

here is the output with GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)

value of $? : 1
value of BASH_REMATCH :
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)

I've read a lot of post here and elsewhere regarding the behaviors of the oparator in =~ and I can't find anyone who haves the same problem. I saw that there were major changes in bash 3.2 but as far as I see it should work from 3.2 onward.

1
Please take note that I've already tried to include it in a case statement, as in: "case $line in ^\[.*\]$ )" - vinni_f

1 Answers

2
votes

Looks like some form of escaping problem.

This works here (bash version 3.2.25(1)-release):

line="[foo]"
bar="^\[.*\]$"
[[ $line =~ $bar ]] && echo "regex matched"

This also appears to work:

[[ $line =~ ^\\[.*\\]$ ]] && echo "regex matched"