bash - BASH_REMATCH 在 Bash 5.1 中不是只读的有什么用?

标签 bash

我在 release notes of Bash 5.1 中读到:

p. BASH_REMATCH is no longer readonly.

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.

是的,访问正则表达式的匹配项非常有用:

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

但是,我看不出这个消息在 Bash 5.1 中有什么用。也就是说,BASH_REMATCH 不是只读的有什么意义?

最佳答案

this bug-bash mailing list threadbashdb 的维护者(一个 Bash 调试器)解释说 BASH_REMATCH 的值可能会在调试钩子(Hook)内部发生变化,并且由于该变量是只读的,因此可以通过运行最初再次设置它的命令来重置它,这很棘手又脆弱:

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.

response , Chet 提出让它不是只读的:

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

关于bash - BASH_REMATCH 在 Bash 5.1 中不是只读的有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65669036/

相关文章:

bash - Unix bash 别名在启动 screen 后不起作用

linux - 剪切字符串直到指定字符。狂欢

bash - 通过传递参数来捕获函数?

Linux 导出命令不起作用

bash - Shebang 后跟 rm 命令不是自删除脚本

linux - Sed 没有写入文件

bash - latexmk - 运行 bash 命令来停止 Dropbox 同步

linux - 删除第 N 个字段中编号小于 X 的行

bash - PredictionIO:安装后找不到 Pio 命令

node.js - 在 "npm start"中使用 ~/.bashrc 中的环境变量?