2

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 ^\[.*\]$ )" Commented Mar 6, 2013 at 17:17

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

All right @Mat. Your first solution is working on both versions. I must say that I tried doing: [[ $line =~ "^\[.*\]$" ]] before posting but it was not behaving as expected. Doing bar="^\[.*\]$" then [[ $line =~ $bar ]] works. Do you know what's the difference between these 2 ways of wrinting?
Your second solution does not work in GNU bash, version 4.2.24(1). Merci ;)
I don't really know why what you had didn't work, or, for that matter, why the double-escaped one does (in 3.2). Might be a bug. See this bash FAQ item E14 for some info related to bash versions and that [[ =~ ]] thing. The "stuff it in a variable" trick works well enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.