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])
- X-seq: zsh-users 30264
- From: Roman Perepelitsa <roman.perepelitsa@xxxxxxxxx>
- To: Philippe Altherr <philippe.altherr@xxxxxxxxx>
- Cc: James Widman <james.widman@xxxxxxxxx>, Zsh-Users List <zsh-users@xxxxxxx>, Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx>
- Subject: Re: Defining variables in the caller's environment (was: ERR_RETURN ignored in 'if' in a source'd file [FIXED])
- Date: Tue, 20 May 2025 12:51:51 +0200
- Archived-at: <https://zsh.org/users/30264>
- In-reply-to: <CAGdYchvkvCTV0HQ1RqTCP8pTX8pDbc6+P=5mrPq3UGiUfeODzw@mail.gmail.com>
- List-id: <zsh-users.zsh.org>
- References: <CAGdYchvkvCTV0HQ1RqTCP8pTX8pDbc6+P=5mrPq3UGiUfeODzw@mail.gmail.com>
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