bash - 使 shopt 更改为本地功能

标签 bash shopt

我正在尝试编写一个使用 nocasematch 的 bash 函数,而不更改选项的调用者设置。函数定义为:

is_hello_world() {
  shopt -s nocasematch
  [[ "$1" =~ "hello world" ]] 
}

调用之前:

$ shopt nocasematch
nocasematch     off

调用它:

$ is_hello_world 'hello world' && echo Yes
Yes
$ is_hello_world 'Hello World' && echo Yes
Yes

正如预期的那样,但是现在调用者的 nocasematch 发生了变化:

$ shopt nocasematch
nocasematch     on

是否有任何简单的方法可以使选项在函数本地更改?

我知道我可以检查 shopt -q 的返回值,但这仍然意味着函数应该记住它并在退出前重置它。

最佳答案

函数体可以是任何复合命令,而不仅仅是组命令 ({})。使用子外壳:

is_hello_world() (
  shopt -s nocasematch
  [[ "$1" =~ "hello world" ]] 
)

关于bash - 使 shopt 更改为本地功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12179633/

相关文章:

linux - screen self 删除

bash - #$ 在 bash 中做什么? (又名 : Hash dollar sign, 英镑美元符号)

linux - Bash:将程序输出打印到文件,而不是在屏幕上

bash - 由引号和未引号部分组成的字符串中的通配符扩展(通配符)

bash - 终端中设置的 globstar 未传播到脚本

Bash shopt xpg_echo

linux - wget 在命令行中工作,但不在 bash 中检索文件

arrays - nullglob 和数组

bash - 分配给位置参数