zsh

How to do a set -u locally?


I would like to turn on

set -u

only inside the body of one zsh function. At the end of the function, it should be restored to its previous state.

I reckon that I have to do a

setopt localoptions ????

inside the function, but what comes at the place of the ???? ? From the zsh manpage, I found an explanation for the option UNSET, but this corresponds to set +u, not set -u.

UPDATE:

Based on the answer given by chepner, I also tried:

set -u
foo() {
 setopt NO_UNSET LOCAL_OPTIONS
 echo $xx
}
bar() {
 setopt localoptions nounset
 echo $xx
}

But both functions, when invoked, abort with xx: parameter not set


Solution

  • set -u is equivalent to setopt no_unset and set +u is equivalent to setopt unset. You've inverted the meaning.

    set -u
    foo() {
     setopt local_options unset
     echo $xx
    }
    foo # prints an empty line
    echo $xx # errors out
    

    Documentation references: