我正在尝试编写一个使用 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/