使小店更改本地功能 [英] Make shopt change local to function

查看:103
本文介绍了使小店更改本地功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a bash function that uses nocasematch without changing the callers setting of the option. The function definition is:

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已更改:

As expected, but now nocasematch of the caller has changed:

$ shopt nocasematch
nocasematch     on

是否有任何简便的方法可以将选项局部更改为功能?

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

I know I can check the return value of shopt -q but that still means the function should remember this and reset it before exit.

推荐答案

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

The function body can be any compound command, not just a group command ( {} ). Use a sub-shell:

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

这篇关于使小店更改本地功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆