Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Defining variables in the caller's environment (was: ERR_RETURN ignored in 'if' in a source'd file [FIXED])



On Tue, May 20, 2025 at 1:09 AM Philippe Altherr
<philippe.altherr@xxxxxxxxx> 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




Messages sorted by: Reverse Date, Date, Thread, Author