Re: Defining variables in the caller's environment (was: ERR_RETURN ignored in 'if' in a source'd file [FIXED])
Roman Perepelitsa <[email protected]>
| Newsgroups | gmane.comp.shells.zsh.devel,gmane.comp.shells.zsh.user |
|---|---|
| Message-ID | <CAN=4vMrc9u4NBEuCBhfPQFt8qLSWxOENTwfVn3j10dAB_JpsEQ@mail.gmail.com> |
On Tue, May 20, 2025 at 1:09 AM Philippe Altherr <[email protected]> wrote: > > - Techniques to define variables in the caller's environment An alternative technique that relies on `typeset -p` to handle quoting: function define-vars() { local -A var1=("$1" "$2") local -i var2=42 # Set var1 and var2 in the caller's scope. trap "$(typeset -p -- var1 var2)" EXIT } function main() { define-vars 'x' 'y $ z' typeset -p var1 var2 # check what we've got } In Zsh 5.10 and above, $( ... ) can be replaced with ${ ... } to avoid forking. The trap trick can be replaced with sourcing (not that it gives any advantages): function define-vars() { local -A var1=("$1" "$2") local -i var2=42 typeset -p -- var1 var2 } function main() { source <(define-vars 'x' 'y $ z') typeset -p var1 var2 } Roman