5

I'm writing a zsh shell function (as opposed to a script) where I would really like the extended_glob option to be enabled. But since the function runs in the caller's context, I don't want to clobber their settings.

What I'd like to do is conditionally enabled extended_glob as long as I need it and then restore it to the user's option. Is there any way to check whether an option is enabled in zsh?

10

You can use the local_options option to automatically restore options when the function exits. This would only be appropriate if your function does not make any other option changes that you intend to persist after the function has finished.

Thus, you could write your function like this:

do_something() {
  setopt local_options extended_glob
  ⋮
}

If you have some other option that you want to persist after the function has returned, you can use the options associative array (from the zsh/parameter module) to easily check and manipulate individual options:

do_something() {
  local eg=$options[extended_glob]
  setopt extended_glob
  ⋮
  options[extended_glob]=$eg
}

If this module is not available in your installation, then you can use the -o test:

do_something() {
  local eg=no
  [[ -o extended_glob ]] && eg=
  setopt extended_glob
  ⋮
  setopt ${eg}extended_glob
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.