命令行上的 Shell 参数扩展在 bash 脚本中不起作用

Ser*_*ndt 2 bash shell-script

考虑以下bash 命令行上的GNU shell 参数扩展,其解释如下:

$ a='hello world    example'

$ echo ${a//+( )/_}
hello_world_example
Run Code Online (Sandbox Code Playgroud)

然而,同样的参数扩展在 bash 脚本中不再起作用。

# !/usr/bin/env bash
a='hello world    example'
echo "${a//+( )/_}"
Run Code Online (Sandbox Code Playgroud)

它导致未更改的字符串:

hello world    example
Run Code Online (Sandbox Code Playgroud)

我已经从一个更简单的参数扩展中了解到命令" "后面的双引号echo是必需的,尽管我不知道为什么。

但是,要让这个特定的参数扩展在 bash 脚本中工作,还需要做些什么?为什么?

ilk*_*chu 6

+(...)扩展 globs 的一部分,您需要使用shopt -s extglob.

如果它在您的交互式 shell 中工作,则您可能shopt -s extglob在 shell 的启动文件之一中,例如bashrc. 但是常规的非交互式 shell 不会读取这些内容,因此那里的任何设置都不会生效,您需要将其明确地放入脚本中。最好单独一行,因为它如何改变解析器的工作方式有一些怪癖,请参阅: 设置 shopt extglob 的范围限制是什么。和其他选择?