Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of BASH_REMATCH not being readonly from Bash 5.1?

Tags:

bash

I read in the release notes of Bash 5.1:

p. BASH_REMATCH is no longer readonly.

As explained in the Bash Reference Manual:

The array variable BASH_REMATCH records which parts of the string matched the pattern. The element of BASH_REMATCH with index 0 contains the portion of the string matching the entire regular expression. Substrings matched by parenthesized subexpressions within the regular expression are saved in the remaining BASH_REMATCH indices. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

And yes, it is very useful to access the matches of a regular expression:

$ DESERT=pie-cake_berry_cream-sirup
$ [[ $DESERT =~ _(.*)_ ]] && echo "${BASH_REMATCH[1]}"
berry

However, I cannot see what is the use of this news in Bash 5.1. That is, what is the point of BASH_REMATCH not being readonly?

like image 749
fedorqui 'SO stop harming' Avatar asked Nov 19 '25 23:11

fedorqui 'SO stop harming'


1 Answers

In this bug-bash mailing list thread, the maintainer of bashdb (a Bash debugger) explains that the value of BASH_REMATCH might change inside a debug hook, and since the variable is read-only, resetting it happens by running the command that initially set it again, which is tricky and fragile:

Current in bash 5.0 and earlier, the value of BASH_REMATCH might chanted inside a debug hook.

Since BASH_REMATCH is read-only, resetting the value on hook return to the debugged program is a bit tricky and fragile...

[...]

The way that bashdb currently resets BASH_REMATCH is to reissue the command that caused the value to get initially set. That is fragile since this set on exit between stepping from the time BASH_REMATCH was set until the time it is last used. In between variables used in the regular expression may have changed.

[...]

Restoring it is just as tricky. As I hope you see all of this is a bit fragile.

In the response, Chet offers to make it not read-only:

How about we just make it not read-only? The shell will still set it when it does regexp matching.

like image 165
Benjamin W. Avatar answered Nov 22 '25 17:11

Benjamin W.